From b162097c3c7f5e5174eb70124de8888669775dbd Mon Sep 17 00:00:00 2001 From: andy-ms Date: Fri, 19 May 2017 20:06:08 -0700 Subject: [PATCH 1/5] 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 | 5519 +++++++++++++++------- lib/tsserver.js | 6554 +++++++++++++++----------- lib/tsserverlibrary.d.ts | 320 +- lib/tsserverlibrary.js | 6540 +++++++++++++++----------- lib/typescript.d.ts | 279 +- lib/typescript.js | 7189 +++++++++++++++++------------ lib/typescriptServices.d.ts | 279 +- lib/typescriptServices.js | 7189 +++++++++++++++++------------ 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, 27711 insertions(+), 13451 deletions(-) diff --git a/lib/cancellationToken.js b/lib/cancellationToken.js index 0e37b0689e02f..ec9453bb00c99 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 80e09b844cb59..9848b92063702 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 1fe1a0e0ca16f..551698607ca79 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 29b12d91e2445..440897038ef73 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 737357fef6d92..a22ca2e9d804a 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 dae59bc9ae32d..d70049b130983 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 c0254f1dc2ca2..50a38686a90a3 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 1d19198d1d1f3..f359e519ab13e 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 76dc84306ed10..4d2428a59ba14 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 d285df3f4db7a..70db6a7845295 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 693a32dc98bf9..1d92d339b9d4f 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; + } + 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; } } - if (isDeclaration(parent)) { - return parent.name === name; + else { + return declaration.name; } - return false; } - ts.isDeclarationName = isDeclarationName; + 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; - } - else if (options.newLine === 1) { - return lineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 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); - return ts.createTypeReferenceNode(name, undefined); - } - if (type.flags & 16384) { - 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 (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); - } - else { + 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.right = qualifiedNamePart; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } + else { + 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) { + 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 ? 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); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : 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 ? 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); + } + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + 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)); + } + } + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); } - 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 (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 & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 4096 && (!strictNullChecks || t & 4096)) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) - return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) - return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { + if (s & 1) return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) 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,6 +33487,57 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var type = checkNonNullExpression(left); + if (isTypeAny(type) || type === silentNeverType) { + return type; + } + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + return apparentType; + } + var prop = getPropertyOfType(apparentType, right.text); + if (!prop) { + var stringIndexType = getIndexTypeOfType(apparentType, 0); + if (stringIndexType) { + return stringIndexType; + } + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); + } + return unknownType; + } + if (prop.valueDeclaration) { + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); + } + if (prop.valueDeclaration.kind === 229 && + node.parent && node.parent.kind !== 159 && + !ts.isInAmbientContext(prop.valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); + } + } + markPropertyAsReferenced(prop); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + var propType = getDeclaredOrApparentType(prop, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); + return unknownType; + } + } + if (node.kind !== 179 || assignmentKind === 1 || + !(prop.flags & (3 | 4 | 98304)) && + !(prop.flags & 8192 && propType.flags & 65536)) { + return propType; + } + var flowType = getFlowTypeOfReference(node, propType); + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } function reportNonexistentProperty(propNode, containingType) { var errorInfo; if (containingType.flags & 65536 && !(containingType.flags & 8190)) { @@ -31814,15 +33549,80 @@ var ts; } } } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + 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 (getCheckFlags(prop) & 1) { + if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } else { @@ -31839,57 +33639,6 @@ var ts; } return false; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { - return apparentType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0); - if (stringIndexType) { - return stringIndexType; - } - if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); - } - return unknownType; - } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); - } - if (prop.valueDeclaration.kind === 229 && - node.parent && node.parent.kind !== 159 && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); - } - } - markPropertyAsReferenced(prop); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); - return unknownType; - } - } - if (node.kind !== 179 || assignmentKind === 1 || - !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 65536)) { - return propType; - } - var flowType = getFlowTypeOfReference(node, propType); - return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; - } 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; - } - 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; + } + 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); } - 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,46 +56315,51 @@ 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("', '") + "'"]; - } - 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]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - } - 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]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, 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]; + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); } } + return sourceFile; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); - } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); + else { + 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; } } + 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]; + } + 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) { fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); @@ -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 05f4c1e5fd1af..ae6c3c8dc0791 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; + } + 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; } } - if (isDeclaration(parent)) { - return parent.name === name; + else { + return declaration.name; } - return false; } - ts.isDeclarationName = isDeclarationName; + 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; - } - else if (options.newLine === 1) { - return lineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 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); - } - else { + 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.right = qualifiedNamePart; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } + else { + 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) { + 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 ? 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); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : 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 ? 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); + } + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + 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)); + } + } + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); } - 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 (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 & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 4096 && (!strictNullChecks || t & 4096)) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) - return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) - return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { + if (s & 1) return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) 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,6 +33505,57 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var type = checkNonNullExpression(left); + if (isTypeAny(type) || type === silentNeverType) { + return type; + } + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + return apparentType; + } + var prop = getPropertyOfType(apparentType, right.text); + if (!prop) { + var stringIndexType = getIndexTypeOfType(apparentType, 0); + if (stringIndexType) { + return stringIndexType; + } + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); + } + return unknownType; + } + if (prop.valueDeclaration) { + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); + } + if (prop.valueDeclaration.kind === 229 && + node.parent && node.parent.kind !== 159 && + !ts.isInAmbientContext(prop.valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); + } + } + markPropertyAsReferenced(prop); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + var propType = getDeclaredOrApparentType(prop, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); + return unknownType; + } + } + if (node.kind !== 179 || assignmentKind === 1 || + !(prop.flags & (3 | 4 | 98304)) && + !(prop.flags & 8192 && propType.flags & 65536)) { + return propType; + } + var flowType = getFlowTypeOfReference(node, propType); + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } function reportNonexistentProperty(propNode, containingType) { var errorInfo; if (containingType.flags & 65536 && !(containingType.flags & 8190)) { @@ -32977,15 +33567,80 @@ var ts; } } } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + 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 (getCheckFlags(prop) & 1) { + if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } else { @@ -33002,57 +33657,6 @@ var ts; } return false; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { - return apparentType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0); - if (stringIndexType) { - return stringIndexType; - } - if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); - } - return unknownType; - } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); - } - if (prop.valueDeclaration.kind === 229 && - node.parent && node.parent.kind !== 159 && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); - } - } - markPropertyAsReferenced(prop); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); - return unknownType; - } - } - if (node.kind !== 179 || assignmentKind === 1 || - !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 65536)) { - return propType; - } - var flowType = getFlowTypeOfReference(node, propType); - return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; - } 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; - } - 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; + } + 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); } - 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,46 +56333,51 @@ 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("', '") + "'"]; - } - 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]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - } - 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]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, 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]; + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); } } + return sourceFile; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); - } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); + else { + 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; } } + 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]; + } + 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) { fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); @@ -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 (include && !json["include"]) { - json["include"] = include; + if (exclude) { + json.exclude = exclude; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (files) { + json.files = files; } - if (files && !json["files"]) { - json["files"] = files; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - 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); - } - 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); + 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; } - 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)); - }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); - }; - TokenRange.FromRange = function (f, to, except) { - if (except === void 0) { except = []; } - return new TokenRange(new TokenRangeAccess(f, to, except)); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.AllTokens = function () { - return new TokenRange(new TokenAllAccess()); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - 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); + return deleteIdentifier(); + case 149: + case 240: + return deleteNode(token.parent); + default: + return deleteDefault(); + } + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } + } + 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); } - else { - return deleteNodeInList(token.parent); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29) { + return deleteRange(typeParameters); } - case 239: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); + 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 { - 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); + return deleteNode(importClause.name); } - 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); + } + 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 }); } - } - break; - case 149: - case 240: - return deleteNode(token.parent); - } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + 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); - } - 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)); - } - } - 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; + 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); + } + } + 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)); } - 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; - } - 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; + if (node.kind === 237) { + return node; + } + node = node.parent; } + return undefined; } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); - } - return ts.getSymbolId(symbol); + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + 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); } - 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; - } - else { - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); + 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; } else { - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); + namedImportDeclaration = declaration; } + existingModuleSpecifier = declaration.moduleSpecifier.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + else { + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - 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)); + } + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + } + 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 { + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248) { + return declaration.moduleReference.expression.getText(); } - else { - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + 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 actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248) { - return declaration.moduleReference.expression.getText(); - } - 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(); + 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(); } - 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"); + 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; - } + } + 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 }); + } + 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; + } } - 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; } - 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; + 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); - } + 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 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 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); } } } - 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); - } + } + 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; + catch (e) { } } + return relativeFileName; } - 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); + } + 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 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; + 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 - }; } } - }); + 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 189883c63e632..643a9e80d069c 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 52c8a2207c472..e23edda9295b0 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]; - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + 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 (include && !json["include"]) { - json["include"] = include; + if (exclude) { + json.exclude = exclude; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (files) { + json.files = files; } - if (files && !json["files"]) { - json["files"] = files; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - 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; + } + 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; } } - if (isDeclaration(parent)) { - return parent.name === name; + else { + return declaration.name; } - return false; } - ts.isDeclarationName = isDeclarationName; + 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; - } - else if (options.newLine === 1) { - return lineFeed; + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 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); - return ts.createTypeReferenceNode(name, undefined); - } - if (type.flags & 16384) { - 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 (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); - } - else { + 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.right = qualifiedNamePart; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); qualifiedName = ts.createQualifiedName(qualifiedName, undefined); } + else { + 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) { + 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 ? 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); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : 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 ? 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); + } + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119) { + returnTypeNode = undefined; + } + } + else if (!returnTypeNode) { + returnTypeNode = ts.createKeywordTypeNode(119); } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + 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)); + } + } + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); } - 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 (s & 262178 && t & 2) return true; - if (source.flags & 262178 && target.flags & 2) + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 340 && target.flags & 4) + if (s & 84 && t & 4) return true; - if (source.flags & 136 && target.flags & 8) + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) + if (s & 136 && t & 8) return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + 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 & 4096 && (!strictNullChecks || target.flags & 4096)) + if (s & 4096 && (!strictNullChecks || t & 4096)) return true; - if (source.flags & 32768 && target.flags & 16777216) + if (s & 32768 && t & 16777216) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) - return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + if (s & 1) return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) 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,6 +34854,57 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var type = checkNonNullExpression(left); + if (isTypeAny(type) || type === silentNeverType) { + return type; + } + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + return apparentType; + } + var prop = getPropertyOfType(apparentType, right.text); + if (!prop) { + var stringIndexType = getIndexTypeOfType(apparentType, 0); + if (stringIndexType) { + return stringIndexType; + } + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); + } + return unknownType; + } + if (prop.valueDeclaration) { + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); + } + if (prop.valueDeclaration.kind === 229 && + node.parent && node.parent.kind !== 159 && + !ts.isInAmbientContext(prop.valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); + } + } + markPropertyAsReferenced(prop); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + var propType = getDeclaredOrApparentType(prop, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); + return unknownType; + } + } + if (node.kind !== 179 || assignmentKind === 1 || + !(prop.flags & (3 | 4 | 98304)) && + !(prop.flags & 8192 && propType.flags & 65536)) { + return propType; + } + var flowType = getFlowTypeOfReference(node, propType); + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } function reportNonexistentProperty(propNode, containingType) { var errorInfo; if (containingType.flags & 65536 && !(containingType.flags & 8190)) { @@ -34323,15 +34916,80 @@ var ts; } } } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + 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 (getCheckFlags(prop) & 1) { + if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } else { @@ -34348,57 +35006,6 @@ var ts; } return false; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { - return apparentType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0); - if (stringIndexType) { - return stringIndexType; - } - if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); - } - return unknownType; - } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); - } - if (prop.valueDeclaration.kind === 229 && - node.parent && node.parent.kind !== 159 && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); - } - } - markPropertyAsReferenced(prop); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); - return unknownType; - } - } - if (node.kind !== 179 || assignmentKind === 1 || - !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 65536)) { - return propType; - } - var flowType = getFlowTypeOfReference(node, propType); - return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; - } 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; - } - 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; + } + 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); } - 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,46 +57682,51 @@ 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("', '") + "'"]; - } - 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]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - } - 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]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, 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]; + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); } } + return sourceFile; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); - } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); + else { + 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; } } + 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]; + } + 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) { fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); @@ -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); - } - 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); + 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; } - 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); + return deleteIdentifier(); + case 149: + case 240: + return deleteNode(token.parent); + default: + return deleteDefault(); + } + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } + } + 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); } - else { - return deleteNodeInList(token.parent); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29) { + return deleteRange(typeParameters); } - case 239: - var importClause = token.parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); + 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 { - 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); - } + 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); + } + 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 }); } - } - break; - case 149: - case 240: - return deleteNode(token.parent); - } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + 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); - } - 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)); - } - } - 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; + 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); + } + } + 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)); } - 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; - } - 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; + if (node.kind === 237) { + return node; + } + node = node.parent; } + return undefined; } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); - } - return ts.getSymbolId(symbol); + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + 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); } - 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; - } - else { - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); + 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; } else { - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); + namedImportDeclaration = declaration; } + existingModuleSpecifier = declaration.moduleSpecifier.getText(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + else { + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - 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)); + } + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + } + 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 { + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248) { + return declaration.moduleReference.expression.getText(); } - else { - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + 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 actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248) { - return declaration.moduleReference.expression.getText(); - } - 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(); + 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(); } - 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"); + 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; - } + } + 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 }); + } + 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; + } } - 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; } - 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; + 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); - } + 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 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 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); } } } - 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); - } + } + 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; + catch (e) { } } + return relativeFileName; } - 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); + } + 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 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; + 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 - }; } } - }); + 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; + } + else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + args.startPosition = startPosition; + } + if (args.endPosition !== undefined) { + endPosition = args.endPosition; } - function getEndPosition() { - return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + 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 2f11d458e2073..5853aafb94642 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 NumberLiteralType extends LiteralType { + value: number; } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; + 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 4fe0eb9bf25ae..a73895f4f74e7 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; + } + 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; } } - if (isDeclaration(parent)) { - return parent.name === name; + else { + return declaration.name; } - return false; } - ts.isDeclarationName = isDeclarationName; + 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); - } - else { + 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.right = qualifiedNamePart; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); } + else { + 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); + } + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + returnTypeNode = undefined; + } } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 /* AnyKeyword */ ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + 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)); + } + } + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); } - 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 */) - return true; - if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) + if (s & 1 /* Any */) 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)) { + // 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; - } } 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,6 +38915,61 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var type = checkNonNullExpression(left); + if (isTypeAny(type) || type === silentNeverType) { + return type; + } + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { + // handle cases when type is Type parameter with invalid or any constraint + return apparentType; + } + var prop = getPropertyOfType(apparentType, right.text); + if (!prop) { + var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */); + if (stringIndexType) { + return stringIndexType; + } + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); + } + return unknownType; + } + if (prop.valueDeclaration) { + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); + } + if (prop.valueDeclaration.kind === 229 /* ClassDeclaration */ && + node.parent && node.parent.kind !== 159 /* TypeReference */ && + !ts.isInAmbientContext(prop.valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); + } + } + markPropertyAsReferenced(prop); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + var propType = getDeclaredOrApparentType(prop, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); + return unknownType; + } + } + // Only compute control flow type if this is a property access expression that isn't an + // assignment target, and the referenced property was declared as a variable, property, + // accessor, or optional method. + if (node.kind !== 179 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && + !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { + return propType; + } + 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 */)) { @@ -38346,15 +38981,99 @@ var ts; } } } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + 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 (getCheckFlags(prop) & 1 /* Instantiated */) { + if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } else { @@ -38371,61 +39090,6 @@ var ts; } return false; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { - // handle cases when type is Type parameter with invalid or any constraint - return apparentType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */); - if (stringIndexType) { - return stringIndexType; - } - if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); - } - return unknownType; - } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); - } - if (prop.valueDeclaration.kind === 229 /* ClassDeclaration */ && - node.parent && node.parent.kind !== 159 /* TypeReference */ && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); - } - } - markPropertyAsReferenced(prop); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); - return unknownType; - } - } - // Only compute control flow type if this is a property access expression that isn't an - // assignment target, and the referenced property was declared as a variable, property, - // accessor, or optional method. - if (node.kind !== 179 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { - return propType; - } - var flowType = getFlowTypeOfReference(node, propType); - return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; - } 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 */); - } - } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + // 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 */); + } + // 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 & 5 /* InvalidGenerator */) === 1 /* Generator */) { - if (functionFlags & 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 2048 /* AsyncGenerator */); - } - else if (languageVersion < 2 /* ES2015 */) { + 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 */); + } + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + } + // 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; - } - 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; + } + 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); } - 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,46 +68651,53 @@ 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("', '") + "'"]; - } - 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]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - } - 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]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, 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]; + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); } } + return sourceFile; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); - } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); + else { + 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; } } + /** 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]; + } + 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) { fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); @@ -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); - // 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")); + 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 (include && !json["include"]) { - json["include"] = include; + if (exclude) { + json.exclude = exclude; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (files) { + json.files = files; } - if (files && !json["files"]) { - json["files"] = files; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - 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; + // 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 _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)); - }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); - }; - 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); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - 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); + return deleteIdentifier(); + case 149 /* PropertyDeclaration */: + case 240 /* NamespaceImport */: + return deleteNode(token.parent); + default: + return deleteDefault(); + } + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } + } + 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); } - else { - // delete import specifier - return deleteNodeInList(token.parent); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { + return deleteRange(typeParameters); } - // 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); + 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 { - // 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); - } + 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); + } + 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 }); } - } - break; - case 149 /* PropertyDeclaration */: - case 240 /* NamespaceImport */: - return deleteNode(token.parent); - } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + 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); - } - 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)); - } - } - // 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; + 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); + } + } + 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)); } - 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; } - } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238 /* ImportDeclaration */) { - return node; - } - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; - } - node = node.parent; + if (node.kind === 237 /* ImportEqualsDeclaration */) { + return node; } - return undefined; + node = node.parent; } + return undefined; } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608 /* Alias */) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); - } - return ts.getSymbolId(symbol); + } + 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); } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + else { + return [getCodeActionForNewImport()]; } - 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; - } - 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 { + 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 foo = require("foo") + // import * as ns from "foo" namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(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(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + else { + // case: + // import foo = require("foo") + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - 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 (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + } + 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 { + // we need to create a new import statement, but the existing module specifier can be reused. + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { + return declaration.moduleReference.expression.getText(); + } + 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 { - // 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(); - } - 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; - } + 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 }); + } + 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; + } } - // 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; } - 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; + 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); - } + 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 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 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); } } } - 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); - } + } + 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; + catch (e) { } } + return relativeFileName; } - 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 */); + } + 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 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; + 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 - }; } } - }); + 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 01d5540db5481..df00c45de24a6 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 NumberLiteralType extends LiteralType { + value: number; } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; + 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 4fe0eb9bf25ae..a73895f4f74e7 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; + } + 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; } } - if (isDeclaration(parent)) { - return parent.name === name; + else { + return declaration.name; } - return false; } - ts.isDeclarationName = isDeclarationName; + 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); - } - else { + 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.right = qualifiedNamePart; + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); } + else { + 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); + } + if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { + returnTypeNode = undefined; + } } - var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 119 /* AnyKeyword */ ? returnTypeNode : undefined; - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny); + 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)); + } + } + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); } - 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 */) - return true; - if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) + if (s & 1 /* Any */) 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)) { + // 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; - } } 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,6 +38915,61 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var type = checkNonNullExpression(left); + if (isTypeAny(type) || type === silentNeverType) { + return type; + } + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { + // handle cases when type is Type parameter with invalid or any constraint + return apparentType; + } + var prop = getPropertyOfType(apparentType, right.text); + if (!prop) { + var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */); + if (stringIndexType) { + return stringIndexType; + } + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); + } + return unknownType; + } + if (prop.valueDeclaration) { + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); + } + if (prop.valueDeclaration.kind === 229 /* ClassDeclaration */ && + node.parent && node.parent.kind !== 159 /* TypeReference */ && + !ts.isInAmbientContext(prop.valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); + } + } + markPropertyAsReferenced(prop); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + var propType = getDeclaredOrApparentType(prop, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); + return unknownType; + } + } + // Only compute control flow type if this is a property access expression that isn't an + // assignment target, and the referenced property was declared as a variable, property, + // accessor, or optional method. + if (node.kind !== 179 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && + !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { + return propType; + } + 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 */)) { @@ -38346,15 +38981,99 @@ var ts; } } } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + 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 (getCheckFlags(prop) & 1 /* Instantiated */) { + if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } else { @@ -38371,61 +39090,6 @@ var ts; } return false; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { - // handle cases when type is Type parameter with invalid or any constraint - return apparentType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */); - if (stringIndexType) { - return stringIndexType; - } - if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); - } - return unknownType; - } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); - } - if (prop.valueDeclaration.kind === 229 /* ClassDeclaration */ && - node.parent && node.parent.kind !== 159 /* TypeReference */ && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); - } - } - markPropertyAsReferenced(prop); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getTypeOfSymbol(prop); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); - return unknownType; - } - } - // Only compute control flow type if this is a property access expression that isn't an - // assignment target, and the referenced property was declared as a variable, property, - // accessor, or optional method. - if (node.kind !== 179 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { - return propType; - } - var flowType = getFlowTypeOfReference(node, propType); - return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; - } 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 */); - } - } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + // 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 */); + } + // 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 & 5 /* InvalidGenerator */) === 1 /* Generator */) { - if (functionFlags & 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 2048 /* AsyncGenerator */); - } - else if (languageVersion < 2 /* ES2015 */) { + 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 */); + } + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + } + // 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; - } - 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; + } + 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); } - 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,46 +68651,53 @@ 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("', '") + "'"]; - } - 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]; + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; } - } - 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]; + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + fail(ts.Diagnostics.File_0_not_found, 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]; + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); } } + return sourceFile; } - if (diagnostic) { - if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); - } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); + else { + 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; } } + /** 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]; + } + 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) { fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); @@ -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); - // 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")); + 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 (include && !json["include"]) { - json["include"] = include; + if (exclude) { + json.exclude = exclude; } - if (exclude && !json["exclude"]) { - json["exclude"] = exclude; + if (files) { + json.files = files; } - if (files && !json["files"]) { - json["files"] = files; + if (compileOnSave !== undefined) { + json.compileOnSave = compileOnSave; } - 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; + // 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 _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)); - }; - TokenRange.FromTokens = function (tokens) { - return new TokenRange(new TokenValuesAccess(tokens)); - }; - 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); + TokenAllExceptAccess.prototype.GetTokens = function () { + var _this = this; + return allTokens.filter(function (t) { return t !== _this.except; }); }; - TokenRange.prototype.toString = function () { - return this.tokenAccess.toString(); + TokenAllExceptAccess.prototype.Contains = function (token) { + return token !== this.except; }; - 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); + return deleteIdentifier(); + case 149 /* PropertyDeclaration */: + case 240 /* NamespaceImport */: + return deleteNode(token.parent); + default: + return deleteDefault(); + } + function deleteDefault() { + if (ts.isDeclarationName(token)) { + return deleteNode(token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return deleteNode(token.parent.parent); + } + else { + return undefined; + } + } + 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); } - else { - // delete import specifier - return deleteNodeInList(token.parent); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end); + if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { + return deleteRange(typeParameters); } - // 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); + 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 { - // 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); - } + 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); + } + 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 }); } - } - break; - case 149 /* PropertyDeclaration */: - case 240 /* NamespaceImport */: - return deleteNode(token.parent); - } - if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + 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); - } - 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)); - } - } - // 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; + 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); + } + } + 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)); } - 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; } - } - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238 /* ImportDeclaration */) { - return node; - } - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; - } - node = node.parent; + if (node.kind === 237 /* ImportEqualsDeclaration */) { + return node; } - return undefined; + node = node.parent; } + return undefined; } - function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608 /* Alias */) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); - } - return ts.getSymbolId(symbol); + } + 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); } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + else { + return [getCodeActionForNewImport()]; } - 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; - } - 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 { + 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 foo = require("foo") + // import * as ns from "foo" namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(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(); } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + else { + // case: + // import foo = require("foo") + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); } - 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 (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + } + 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 { + // we need to create a new import statement, but the existing module specifier can be reused. + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { + return declaration.moduleReference.expression.getText(); + } + 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 { - // 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(); - } - 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; - } + 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 }); + } + 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; + } } - // 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; } - 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; + 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); - } + 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 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 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); } } } - 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); - } + } + 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; + catch (e) { } } + return relativeFileName; } - 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 */); + } + 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 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; + 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 - }; } } - }); + 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 f610c4fd2738f..4efda1e469e42 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 e29261f724446..aca52422e4494 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 8d85ad125d588..de124714d68e0 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 9580d679fba1d..42945cb592cae 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 47a57e4d1016f..672b484055f6e 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 2fdc567b9bbcf..d4adeaea97492 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 2b45457c1479a..f68c827625453 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 27c47179052f3..6091c0b2d039b 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 67bacaeadd00e..910c31c36b339 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 6c64ce5b9ba65..6f0b3baf53216 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 0555ed93c3f4a..4a3f8769b6198 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 f94818da36c58f9fc0d6d535677f6500a096f6de Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 22 May 2017 10:40:59 -0700 Subject: [PATCH 2/5] 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 | 76 ++++++++++---------- 5 files changed, 167 insertions(+), 259 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index fc50e71478eab..7e2387ed6361b 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 de124714d68e0..c51743e1c392b 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 bae53dcafe8a0..846607cd5caf1 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 0deff25321206..acee8fe4b0eb0 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 6f0b3baf53216..6e6fa245e37d4 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 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"; - - public static 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"; + export const enum ScriptElementKindModifier { + none = "", + publicMemberModifier = "public", + privateMemberModifier = "private", + protectedMemberModifier = "protected", + exportedModifier = "export", + ambientModifier = "declare", + staticModifier = "static", + abstractModifier = "abstract", + } + + export const enum ClassificationTypeNames { + comment = "comment", + identifier = "identifier", + keyword = "keyword", + numericLiteral = "number", + operator = "operator", + stringLiteral = "string", + whiteSpace = "whitespace", + text = "text", + + punctuation = "punctuation", + + 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 3/5] 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 a505c3ee7be0b..74d1f5d064084 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 c51743e1c392b..d398555408bb0 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 4/5] 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 d398555408bb0..8a75311c5d13b 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 5/5] 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 74d1f5d064084..db33d87f087d1 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 8a75311c5d13b..4e474edd0c441 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",