diff --git a/lib/cancellationToken.js b/lib/cancellationToken.js index 0e37b0689e..ec9453bb00 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 1a8b1d7283..c99bf56ef4 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -236,7 +236,7 @@ interface ObjectConstructor { * Returns the names of the enumerable properties and methods of an object. * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - keys(o: any): string[]; + keys(o: {}): string[]; } /** @@ -1000,12 +1000,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: T[][]): T[]; + concat(...items: ReadonlyArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[])[]): T[]; + concat(...items: (T | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1119,12 +1119,12 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: T[][]): T[]; + concat(...items: ReadonlyArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[])[]): T[]; + concat(...items: (T | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. diff --git a/lib/lib.es2015.symbol.wellknown.d.ts b/lib/lib.es2015.symbol.wellknown.d.ts index 1d17534723..f323260bf8 100644 --- a/lib/lib.es2015.symbol.wellknown.d.ts +++ b/lib/lib.es2015.symbol.wellknown.d.ts @@ -130,7 +130,7 @@ interface Map { readonly [Symbol.toStringTag]: "Map"; } -interface WeakMap{ +interface WeakMap { readonly [Symbol.toStringTag]: "WeakMap"; } diff --git a/lib/lib.es2016.full.d.ts b/lib/lib.es2016.full.d.ts index 09220599d5..07c6a3e828 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"; +} + + ///////////////////////////// /// DOM APIs diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index 6c2f260664..331f822c6f 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -25,6 +25,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"; +} + + ///////////////////////////// /// DOM APIs diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index f628dc4fe8..8353dc1500 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -236,7 +236,7 @@ interface ObjectConstructor { * Returns the names of the enumerable properties and methods of an object. * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - keys(o: any): string[]; + keys(o: {}): string[]; } /** @@ -1000,12 +1000,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: T[][]): T[]; + concat(...items: ReadonlyArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[])[]): T[]; + concat(...items: (T | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1119,12 +1119,12 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: T[][]): T[]; + concat(...items: ReadonlyArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[])[]): T[]; + concat(...items: (T | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 588c609a16..b44acacc87 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -236,7 +236,7 @@ interface ObjectConstructor { * Returns the names of the enumerable properties and methods of an object. * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - keys(o: any): string[]; + keys(o: {}): string[]; } /** @@ -1000,12 +1000,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: T[][]): T[]; + concat(...items: ReadonlyArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[])[]): T[]; + concat(...items: (T | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1119,12 +1119,12 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: T[][]): T[]; + concat(...items: ReadonlyArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[])[]): T[]; + concat(...items: (T | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -5689,7 +5689,7 @@ interface Map { readonly [Symbol.toStringTag]: "Map"; } -interface WeakMap{ +interface WeakMap { readonly [Symbol.toStringTag]: "WeakMap"; } diff --git a/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts index 4d06a07f65..f7b59da300 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"; +} + + ///////////////////////////// /// DOM APIs diff --git a/lib/tsc.js b/lib/tsc.js index 9ad790d138..cf9717975c 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -14,14 +14,453 @@ and limitations under the License. ***************************************************************************** */ "use strict"; +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; var 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["JSDocNullableType"] = 270] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 292] = "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"] = 285] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "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["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; + 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"; @@ -46,6 +485,47 @@ var ts; 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"] = 4] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + })(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"; @@ -60,6 +540,230 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; + SymbolFlags[SymbolFlags["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"] = 2097152] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; + SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; + SymbolFlags[SymbolFlags["Classifiable"] = 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 InternalSymbolName; + (function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["Resolving"] = "__resolving__"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); + var NodeCheckFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["String"] = 2] = "String"; + TypeFlags[TypeFlags["Number"] = 4] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; + TypeFlags[TypeFlags["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 InferencePriority; + (function (InferencePriority) { + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; + })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + var InferenceFlags; + (function (InferenceFlags) { + InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; + InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); + var SpecialPropertyAssignmentKind; + (function (SpecialPropertyAssignmentKind) { + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -81,6 +785,310 @@ var ts; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + ScriptKind[ScriptKind["External"] = 5] = "External"; + ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["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["Ts"] = ".ts"; + Extension["Tsx"] = ".tsx"; + Extension["Dts"] = ".d.ts"; + Extension["Js"] = ".js"; + Extension["Jsx"] = ".jsx"; + })(Extension = ts.Extension || (ts.Extension = {})); + var TransformFlags; + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; + TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; + TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; + TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; + TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["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["ExportStar"] = 32768] = "ExportStar"; + 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"] = 32768] = "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) { @@ -143,7 +1151,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.5"; + ts.versionMajorMinor = "2.6"; ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { @@ -257,6 +1265,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; } @@ -428,10 +1442,9 @@ var ts; ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (f(item)) { - array[outIndex] = item; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; outIndex++; } } @@ -477,8 +1490,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -548,11 +1561,13 @@ var ts; ts.sameFlatMap = sameFlatMap; function mapDefined(array, mapFn) { var result = []; - for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); - if (mapped !== undefined) { - result.push(mapped); + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } } } return result; @@ -620,8 +1635,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; if (predicate(v)) { return true; } @@ -646,8 +1661,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var item = array_6[_i]; + loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -735,8 +1750,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var v = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -996,8 +2011,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var value = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -1157,11 +2172,11 @@ var ts; ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { var end = start + length; - Debug.assert(start >= 0, "start must be non-negative, is " + start); - Debug.assert(length >= 0, "length must be non-negative, is " + length); + Debug.assertGreaterThanOrEqual(start, 0); + Debug.assertGreaterThanOrEqual(length, 0); if (file) { - Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); - Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + Debug.assertLessThanOrEqual(start, file.text.length); + Debug.assertLessThanOrEqual(end, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -1370,19 +2385,23 @@ var ts; return normalized; } function normalizePath(path) { + return normalizePathAndParts(path).path; + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { path = normalizeSlashes(path); var rootLength = getRootLength(path); var root = path.substr(0, rootLength); - var normalized = getNormalizedParts(path, rootLength); - if (normalized.length) { - var joinedParts = root + normalized.join(ts.directorySeparator); - return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts; + var parts = getNormalizedParts(path, rootLength); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; } else { - return root; + return { path: root, parts: parts }; } } - ts.normalizePath = normalizePath; + ts.normalizePathAndParts = normalizePathAndParts; function pathEndsWithDirectorySeparator(path) { return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; } @@ -1645,8 +2664,28 @@ var ts; ts.fileExtensionIsOneOf = fileExtensionIsOneOf; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; - var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; - var singleAsteriskRegexFragmentOther = "[^/]*"; + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; function getRegularExpressionForWildcard(specs, basePath, usage) { var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); if (!patterns || !patterns.length) { @@ -1661,18 +2700,16 @@ var ts; if (specs === undefined || specs.length === 0) { return undefined; } - var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; - var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; - var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; return flatMap(specs, function (spec) { - return spec && getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } function isImplicitGlob(lastPathComponent) { return !/[.*?]/.test(lastPathComponent); } ts.isImplicitGlob = isImplicitGlob; - function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; @@ -1704,16 +2741,24 @@ var ts; subpattern += ts.directorySeparator; } if (usage !== "exclude") { + var componentPattern = ""; if (component.charCodeAt(0) === 42) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; component = component.substr(1); } else if (component.charCodeAt(0) === 63) { - subpattern += "[^./]"; + componentPattern += "[^./]"; component = component.substr(1); } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } hasWrittenComponent = true; } @@ -1723,12 +2768,6 @@ var ts; } return subpattern; } - function replaceWildCardCharacterFiles(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); - } - function replaceWildCardCharacterOther(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); - } function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } @@ -1865,14 +2904,7 @@ var ts; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = allSupportedExtensions.slice(0); - for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { - var extInfo = extraFileExtensions_1[_i]; - if (extensions.indexOf(extInfo.extension) === -1) { - extensions.push(extInfo.extension); - } - } - return extensions; + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -1896,6 +2928,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])) { @@ -1989,6 +3028,13 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; + var AssertionLevel; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; @@ -2000,12 +3046,37 @@ var ts; function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { if (verboseDebugInfo) { - message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); } fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; function fail(message, stackCrawlMark) { debugger; var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); @@ -2140,6 +3211,10 @@ var ts; Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; function tryGetExtensionFromPath(path) { return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } @@ -2151,6 +3226,12 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; var FileWatcherEventKind; (function (FileWatcherEventKind) { FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; @@ -2200,7 +3281,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -2324,6 +3405,11 @@ var ts; function readDirectory(path, extensions, excludes, includes, depth) { return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, 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); @@ -3021,6 +4107,8 @@ var ts; Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -3208,6 +4296,7 @@ var ts; Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -3461,6 +4550,8 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), + Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), }; })(ts || (ts = {})); var ts; @@ -5077,19 +6168,6 @@ var ts; return undefined; } ts.getDeclarationOfKind = getDeclarationOfKind; - function findDeclaration(symbol, predicate) { - var declarations = symbol.declarations; - if (declarations) { - for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { - var declaration = declarations_2[_i]; - if (predicate(declaration)) { - return declaration; - } - } - } - return undefined; - } - ts.findDeclaration = findDeclaration; var stringWriter = createSingleLineStringWriter(); var stringWriterAcquired = false; function createSingleLineStringWriter() { @@ -5152,9 +6230,13 @@ var ts; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && - oldResolution.resolvedFileName === newResolution.resolvedFileName; + oldResolution.resolvedFileName === newResolution.resolvedFileName && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function packageIdIsEqual(a, b) { + return a === b || a && b && a.name === b.name && a.version === b.version; + } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -5219,14 +6301,6 @@ var ts; return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; } ts.nodePosToString = nodePosToString; - function getStartPosOfNode(node) { - return node.pos; - } - ts.getStartPosOfNode = getStartPosOfNode; - function isDefined(value) { - return value !== undefined; - } - ts.isDefined = isDefined; function getEndLinePosition(line, sourceFile) { ts.Debug.assert(line >= 0); var lineStarts = ts.getLineStarts(sourceFile); @@ -5257,6 +6331,25 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + if (text.charCodeAt(commentPos + 1) === 47 && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, comment) { + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 33; + } + ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { if (nodeIsMissing(node)) { return node.pos; @@ -5313,15 +6406,20 @@ var ts; var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return '"' + escapeText(node.text) + '"'; + if (node.singleQuote) { + return "'" + escapeText(node.text, 39) + "'"; + } + else { + return '"' + escapeText(node.text, 34) + '"'; + } case 13: - return "`" + escapeText(node.text) + "`"; + return "`" + escapeText(node.text, 96) + "`"; case 14: - return "`" + escapeText(node.text) + "${"; + return "`" + escapeText(node.text, 96) + "${"; case 15: - return "}" + escapeText(node.text) + "${"; + return "}" + escapeText(node.text, 96) + "${"; case 16: - return "}" + escapeText(node.text) + "`"; + return "}" + escapeText(node.text, 96) + "`"; case 8: return node.text; } @@ -5573,13 +6671,9 @@ var ts; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); + return node.kind !== 10 ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; - function getLeadingCommentRangesOfNodeFromText(node, text) { - return ts.getLeadingCommentRanges(text, node.pos); - } - ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; function getJSDocCommentRanges(node, text) { var commentRanges = (node.kind === 146 || node.kind === 145 || @@ -5587,7 +6681,7 @@ var ts; node.kind === 187 || node.kind === 185) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : - getLeadingCommentRangesOfNodeFromText(node, text); + ts.getLeadingCommentRanges(text, node.pos); return ts.filter(commentRanges, function (comment) { return text.charCodeAt(comment.pos + 1) === 42 && text.charCodeAt(comment.pos + 2) === 42 && @@ -5596,8 +6690,9 @@ var ts; } ts.getJSDocCommentRanges = getJSDocCommentRanges; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; - ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { if (158 <= node.kind && node.kind <= 173) { return true; @@ -5824,21 +6919,11 @@ var ts; } ts.getPropertyAssignment = getPropertyAssignment; function getContainingFunction(node) { - while (true) { - node = node.parent; - if (!node || ts.isFunctionLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isFunctionLike); } ts.getContainingFunction = getContainingFunction; function getContainingClass(node) { - while (true) { - node = node.parent; - if (!node || ts.isClassLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isClassLike); } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { @@ -6445,6 +7530,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) { @@ -6642,14 +7733,14 @@ var ts; ts.getAncestor = getAncestor; function getFileReferenceFromReferencePath(comment, commentRange) { var simpleReferenceRegEx = /^\/\/\/\s*/gim; + var isNoDefaultLibRegEx = new RegExp(defaultLibReferenceRegEx.source, "gim"); if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); - var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); + var refLibResult = !refMatchResult && fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); var match = refMatchResult || refLibResult; if (match) { var pos = commentRange.pos + match[1].length + match[2].length; @@ -6680,6 +7771,14 @@ 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; @@ -6830,10 +7929,11 @@ var ts; return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } ts.getOriginalSourceFile = getOriginalSourceFile; - function getOriginalSourceFiles(sourceFiles) { - return ts.sameMap(sourceFiles, getOriginalSourceFile); - } - ts.getOriginalSourceFiles = getOriginalSourceFiles; + 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; @@ -7067,7 +8167,9 @@ var ts; } } ts.createDiagnosticCollection = createDiagnosticCollection; - var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\0": "\\0", "\t": "\\t", @@ -7078,11 +8180,16 @@ var ts; "\n": "\\n", "\\": "\\\\", "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" }); - function escapeString(s) { + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; return s.replace(escapedCharsRegExp, getReplacement); } ts.escapeString = escapeString; @@ -7100,8 +8207,8 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiString(s) { - s = escapeString(s); + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; @@ -7442,7 +8549,7 @@ var ts; var currentDetachedCommentInfo; if (removeComments) { if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); } } else { @@ -7474,9 +8581,8 @@ var ts; } } return currentDetachedCommentInfo; - function isPinnedComment(comment) { - return text.charCodeAt(comment.pos + 1) === 42 && - text.charCodeAt(comment.pos + 2) === 33; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment); } } ts.emitDetachedComments = emitDetachedComments; @@ -7547,9 +8653,13 @@ var ts; } ts.hasModifiers = hasModifiers; function hasModifier(node, flags) { - return (getModifierFlags(node) & flags) !== 0; + return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; function getModifierFlags(node) { if (node.modifierFlagsCache & 536870912) { return node.modifierFlagsCache & ~536870912; @@ -7625,21 +8735,6 @@ var ts; return false; } ts.isDestructuringAssignment = isDestructuringAssignment; - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 71) { - return true; - } - else if (ts.isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } - } function isExpressionWithTypeArgumentsInClassExtendsClause(node) { return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } @@ -7752,72 +8847,6 @@ var ts; return carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; - function isSimpleExpression(node) { - return isSimpleExpressionWorker(node, 0); - } - ts.isSimpleExpression = isSimpleExpression; - function isSimpleExpressionWorker(node, depth) { - if (depth <= 5) { - var kind = node.kind; - if (kind === 9 - || kind === 8 - || kind === 12 - || kind === 13 - || kind === 71 - || kind === 99 - || kind === 97 - || kind === 101 - || kind === 86 - || kind === 95) { - return true; - } - else if (kind === 179) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 180) { - return isSimpleExpressionWorker(node.expression, depth + 1) - && isSimpleExpressionWorker(node.argumentExpression, depth + 1); - } - else if (kind === 192 - || kind === 193) { - return isSimpleExpressionWorker(node.operand, depth + 1); - } - else if (kind === 194) { - return node.operatorToken.kind !== 40 - && isSimpleExpressionWorker(node.left, depth + 1) - && isSimpleExpressionWorker(node.right, depth + 1); - } - else if (kind === 195) { - return isSimpleExpressionWorker(node.condition, depth + 1) - && isSimpleExpressionWorker(node.whenTrue, depth + 1) - && isSimpleExpressionWorker(node.whenFalse, depth + 1); - } - else if (kind === 190 - || kind === 189 - || kind === 188) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 177) { - return node.elements.length === 0; - } - else if (kind === 178) { - return node.properties.length === 0; - } - else if (kind === 181) { - if (!isSimpleExpressionWorker(node.expression, depth + 1)) { - return false; - } - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (!isSimpleExpressionWorker(argument, depth + 1)) { - return false; - } - } - return true; - } - } - return false; - } function formatEnum(value, enumObject, isFlags) { if (value === void 0) { value = 0; } var members = getEnumMembers(enumObject); @@ -7886,18 +8915,6 @@ var ts; return formatEnum(flags, ts.ObjectFlags, true); } ts.formatObjectFlags = formatObjectFlags; - function getRangePos(range) { - return range ? range.pos : -1; - } - ts.getRangePos = getRangePos; - function getRangeEnd(range) { - return range ? range.end : -1; - } - ts.getRangeEnd = getRangeEnd; - function movePos(pos, value) { - return ts.positionIsSynthesized(pos) ? -1 : pos + value; - } - ts.movePos = movePos; function createRange(pos, end) { return { pos: pos, end: end }; } @@ -7926,14 +8943,6 @@ var ts; return range.pos === range.end; } ts.isCollapsedRange = isCollapsedRange; - function collapseRangeToStart(range) { - return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); - } - ts.collapseRangeToStart = collapseRangeToStart; - function collapseRangeToEnd(range) { - return isCollapsedRange(range) ? range : moveRangePos(range, range.end); - } - ts.collapseRangeToEnd = collapseRangeToEnd; function createTokenRange(pos, token) { return createRange(pos, pos + ts.tokenToString(token).length); } @@ -7986,22 +8995,6 @@ var ts; function isInitializedVariable(node) { return node.initializer !== undefined; } - function isMergedWithClass(node) { - if (node.symbol) { - for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 229 && declaration !== node) { - return true; - } - } - } - return false; - } - ts.isMergedWithClass = isMergedWithClass; - function isFirstDeclarationOfKind(node, kind) { - return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; - } - ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; function isWatchSet(options) { return options.watch && options.hasOwnProperty("watch"); } @@ -8202,6 +9195,20 @@ var ts; return ts.hasModifier(node, 92) && node.parent.kind === 152 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { while (node && (node.kind === 176 || ts.isBindingPattern(node))) { node = node.parent; @@ -9282,6 +10289,18 @@ var ts; return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 193: + return true; + case 192: + return expr.operator === 43 || + expr.operator === 44; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; function isExpressionKind(kind) { return kind === 195 || kind === 197 @@ -9466,9 +10485,19 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 207; + || isBlockStatement(node); } ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 207) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 224 || node.parent.kind === 260) { + return false; + } + } + return !ts.isFunctionBlock(node); + } function isModuleReference(node) { var kind = node.kind; return kind === 248 @@ -9530,6 +10559,16 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; + SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; + SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; + SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList"; + SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; + SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; + })(SignatureFlags || (SignatureFlags = {})); var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -11367,11 +12406,31 @@ var ts; var node = parseTokenNode(); return token() === 23 ? undefined : node; } - function parseLiteralTypeNode() { + function parseLiteralTypeNode(negative) { var node = createNode(173); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(192); + unaryMinusExpression.operator = 38; + nextToken(); + } + var expression; + switch (token()) { + case 9: + case 8: + expression = parseLiteralLikeNode(token()); + break; + case 101: + case 86: + expression = parseTokenNode(); + } + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); } function nextTokenIsNumericLiteral() { return nextToken() === 8; @@ -11403,7 +12462,7 @@ var ts; case 86: return parseLiteralTypeNode(); case 38: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(true) : parseTypeReference(); case 105: case 95: return parseTokenNode(); @@ -11452,6 +12511,7 @@ var ts; case 101: case 86: case 134: + case 39: return true; case 38: return lookAhead(nextTokenIsNumericLiteral); @@ -11770,7 +12830,7 @@ var ts; if (!arrowFunction) { return undefined; } - var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); + var isAsync = ts.hasModifier(arrowFunction, 256); var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 36 || lastToken === 17) @@ -11886,7 +12946,7 @@ var ts; function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(187); node.modifiers = parseModifiersForArrowFunction(); - var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); if (!node.parameters) { return undefined; @@ -12619,7 +13679,7 @@ var ts; parseExpected(89); node.asteriskToken = parseOptionalToken(39); var isGenerator = node.asteriskToken ? 1 : 0; - var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -12844,10 +13904,13 @@ var ts; function parseCatchClause() { var result = createNode(260); parseExpected(74); - if (parseExpected(19)) { + if (parseOptional(19)) { result.variableDeclaration = parseVariableDeclaration(); + parseExpected(20); + } + else { + result.variableDeclaration = undefined; } - parseExpected(20); result.block = parseBlock(false); return finishNode(result); } @@ -13851,6 +14914,39 @@ 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["Count"] = 23] = "Count"; + })(ParsingContext || (ParsingContext = {})); + var Tristate; + (function (Tristate) { + Tristate[Tristate["False"] = 0] = "False"; + Tristate[Tristate["True"] = 1] = "True"; + Tristate[Tristate["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); var JSDocParser; (function (JSDocParser) { function parseJSDocTypeExpressionForTests(content, start, length) { @@ -13903,6 +14999,17 @@ var ts; var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; + var JSDocState; + (function (JSDocState) { + JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; + })(JSDocState || (JSDocState = {})); + var PropertyLikeParse; + (function (PropertyLikeParse) { + PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; + })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; start = start || 0; @@ -14535,8 +15642,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -14608,8 +15715,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -14757,10 +15864,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; @@ -14799,6 +15916,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"); @@ -15359,40 +16488,23 @@ var ts; return antecedent; } setFlowNodeReferenced(antecedent); - return { - flags: flags, - expression: expression, - antecedent: antecedent - }; + return { flags: flags, expression: expression, antecedent: antecedent }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); - return { - flags: 128, - switchStatement: switchStatement, - clauseStart: clauseStart, - clauseEnd: clauseEnd, - antecedent: antecedent - }; + return { flags: 128, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { setFlowNodeReferenced(antecedent); - return { - flags: 16, - antecedent: antecedent, - node: node - }; + return { flags: 16, antecedent: antecedent, node: node }; } function createFlowArrayMutation(antecedent, node) { setFlowNodeReferenced(antecedent); - return { - flags: 256, - antecedent: antecedent, - node: node - }; + var res = { flags: 256, antecedent: antecedent, node: node }; + return res; } function finishFlowLabel(flow) { var antecedents = flow.antecedents; @@ -16045,6 +17157,11 @@ var ts; typeLiteralSymbol.members.set(symbol.escapedName, 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.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { @@ -16855,7 +17972,6 @@ var ts; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); var name = node.name; var initializer = node.initializer; var dotDotDotToken = node.dotDotDotToken; @@ -16865,7 +17981,7 @@ var ts; || ts.isThisIdentifier(name)) { transformFlags |= 3; } - if (modifierFlags & 92) { + if (ts.hasModifier(node, 92)) { transformFlags |= 3 | 262144; } if (subtreeFlags & 1048576) { @@ -16894,8 +18010,7 @@ var ts; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 2) { + if (ts.hasModifier(node, 2)) { transformFlags = 3; } else { @@ -16941,7 +18056,10 @@ var ts; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + if (!node.variableDeclaration) { + transformFlags |= 8; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; @@ -17105,9 +18223,8 @@ var ts; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; - var modifierFlags = ts.getModifierFlags(node); var declarationListTransformFlags = node.declarationList.transformFlags; - if (modifierFlags & 2) { + if (ts.hasModifier(node, 2)) { transformFlags = 3; } else { @@ -17406,6 +18523,167 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = ts.createMap(); + var visitedSymbols = ts.createMap(); + return { + walkType: function (type) { + visitedTypes.clear(); + visitedSymbols.clear(); + visitType(type); + return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + }, + walkSymbol: function (symbol) { + visitedTypes.clear(); + visitedSymbols.clear(); + visitSymbol(symbol); + return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + }, + }; + function visitType(type) { + if (!type) { + return; + } + var typeIdString = type.id.toString(); + if (visitedTypes.has(typeIdString)) { + return; + } + visitedTypes.set(typeIdString, type); + var shouldBail = visitSymbol(type.symbol); + if (shouldBail) + return; + if (type.flags & 32768) { + var objectType = type; + var objectFlags = objectType.objectFlags; + if (objectFlags & 4) { + visitTypeReference(type); + } + if (objectFlags & 32) { + visitMappedType(type); + } + if (objectFlags & (1 | 2)) { + visitInterfaceType(type); + } + if (objectFlags & (8 | 16)) { + visitObjectType(objectType); + } + } + if (type.flags & 16384) { + visitTypeParameter(type); + } + if (type.flags & 196608) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 262144) { + visitIndexType(type); + } + if (type.flags & 524288) { + visitIndexedAccessType(type); + } + } + function visitTypeList(types) { + if (!types) { + return; + } + for (var i = 0; i < types.length; i++) { + visitType(types[i]); + } + } + function visitTypeReference(type) { + visitType(type.target); + visitTypeList(type.typeArguments); + } + function visitTypeParameter(type) { + visitType(getConstraintFromTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + visitTypeList(type.types); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + if (signature.typePredicate) { + visitType(signature.typePredicate.type); + } + visitTypeList(signature.typeParameters); + for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + visitTypeList(interfaceT.typeParameters); + visitTypeList(getBaseTypes(interfaceT)); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + var stringIndexType = getIndexTypeOfStructuredType(type, 0); + visitType(stringIndexType); + var numberIndexType = getIndexTypeOfStructuredType(type, 1); + visitType(numberIndexType); + var resolved = resolveStructuredTypeMembers(type); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + visitSignature(signature); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + visitSignature(signature); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return; + } + var symbolIdString = ts.getSymbolId(symbol).toString(); + if (visitedSymbols.has(symbolIdString)) { + return; + } + visitedSymbols.set(symbolIdString, symbol); + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); + if (symbol.flags & 1952) { + symbol.exports.forEach(visitSymbol); + } + ts.forEach(symbol.declarations, function (d) { + if (d.type && d.type.kind === 162) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); +var ts; (function (ts) { function trace(host) { host.trace(ts.formatMessage.apply(undefined, arguments)); @@ -17415,6 +18693,12 @@ var ts; return compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(undefined, r); + } var Extensions; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; @@ -17430,12 +18714,11 @@ var ts; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } - function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); + function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { if (!ts.hasProperty(jsonContent, fieldName)) { @@ -17529,7 +18812,9 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - resolved = realpath(resolved, host, traceEnabled); + if (!options.preserveSymlinks) { + resolved = realPath(resolved, host, traceEnabled); + } if (traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); } @@ -17830,7 +19115,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension }; + return { path: path_1, extension: extension, packageId: undefined }; } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -17851,7 +19136,7 @@ var ts; 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(", ")); + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } @@ -17877,16 +19162,22 @@ var ts; trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); - return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks) { + resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + } + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); - return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } } } - function realpath(path, host, traceEnabled) { + function realPath(path, host, traceEnabled) { if (!host.realpath) { return path; } @@ -17912,7 +19203,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return resolvedFromFile; + return noPackageId(resolvedFromFile); } } if (!onlyRecordFailures) { @@ -17930,6 +19221,9 @@ var ts; return !host.directoryExists || host.directoryExists(directoryName); } ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + } function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -17959,9 +19253,9 @@ var ts; case Extensions.JavaScript: return tryExtension(".js") || tryExtension(".jsx"); } - function tryExtension(extension) { - var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, extension: extension }; + function tryExtension(ext) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, ext: ext }; } } function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { @@ -17984,12 +19278,20 @@ var ts; function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + var packageId; if (considerPackageJson) { var packageJsonPath = pathToPackageJson(candidate); if (directoryExists && state.host.fileExists(packageJsonPath)) { - var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var jsonContent = readJson(packageJsonPath, state.host); + if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { + packageId = { name: jsonContent.name, version: jsonContent.version }; + } + var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); if (fromPackageJson) { - return fromPackageJson; + return withPackageId(packageId, fromPackageJson); } } else { @@ -17999,13 +19301,10 @@ var ts; failedLookupLocations.push(packageJsonPath); } } - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } - function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); if (!file) { return undefined; } @@ -18021,11 +19320,15 @@ var ts; } } var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + if (result) { + ts.Debug.assert(result.packageId === undefined); + return { path: result.path, ext: result.extension }; + } } function resolvedIfExtensionMatches(extensions, path) { - var extension = ts.tryGetExtensionFromPath(path); - return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; } function extensionIsOk(extensions, extension) { switch (extensions) { @@ -18042,7 +19345,7 @@ var ts; } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { @@ -18116,7 +19419,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); } - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -18127,7 +19430,7 @@ var ts; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -18139,7 +19442,7 @@ var ts; return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, false, state)); }); if (resolved_3) { return resolved_3; @@ -18150,7 +19453,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, false, state)); } } } @@ -18294,6 +19597,9 @@ var ts; node = ts.getParseTreeNode(node, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, + getExportSymbolOfSymbol: function (symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, getTypeAtLocation: function (node) { node = ts.getParseTreeNode(node); return node ? getTypeOfNode(node) : unknownType; @@ -18356,6 +19662,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); @@ -18376,11 +19683,10 @@ var ts; getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, getBaseConstraintOfType: getBaseConstraintOfType, - getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, - resolveNameAtLocation: function (location, name, meaning) { - location = ts.getParseTreeNode(location); - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, ts.escapeLeadingUnderscores(name)); + resolveName: function (name, location, meaning) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined); }, + getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -18478,6 +19784,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, @@ -18527,6 +19893,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.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); initializeTypeChecker(); @@ -18790,7 +20169,10 @@ var ts; } return true; } - if (usage.parent.kind === 246) { + if (usage.parent.kind === 246 || (usage.parent.kind === 243 && usage.parent.isExportEquals)) { + return true; + } + if (usage.kind === 243 && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -18820,13 +20202,13 @@ var ts; current.parent.kind === 149 && current.parent.initializer === current; if (initializerOfProperty) { - if (ts.getModifierFlags(current.parent) & 32) { + if (ts.hasModifier(current.parent, 32)) { if (declaration.kind === 151) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 149 && !(ts.getModifierFlags(declaration) & 32); + var isDeclarationInstanceProperty = declaration.kind === 149 && !ts.hasModifier(declaration, 32); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -18906,7 +20288,7 @@ var ts; break; case 149: case 148: - if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 107455)) { @@ -18923,7 +20305,7 @@ var ts; result = undefined; break; } - if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { + if (lastLocation && ts.hasModifier(lastLocation, 32)) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; } @@ -18937,6 +20319,17 @@ var ts; } } break; + case 201: + if (lastLocation === location.expression && location.parent.token === 85) { + var container = location.parent.parent; + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 793064))) { + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return undefined; + } + } + break; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { @@ -18983,7 +20376,7 @@ var ts; lastLocation = location; location = location.parent; } - if (result && nameNotFoundMessage && noUnusedIdentifiers) { + if (result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { result.isReferenced = true; } if (!result) { @@ -19064,7 +20457,7 @@ var ts; error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); return true; } - if (location === container && !(ts.getModifierFlags(location) & 32)) { + if (location === container && !ts.hasModifier(location, 32)) { var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); @@ -19450,7 +20843,6 @@ var ts; if (ambientModule) { return ambientModule; } - var isRelative = ts.isExternalModuleNameRelative(moduleReference); var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); @@ -19469,7 +20861,7 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule && resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -19804,6 +21196,10 @@ var ts; } return false; } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064, false); + return access.accessibility === 0; + } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; @@ -19859,7 +21255,7 @@ var ts; if (!isDeclarationVisible(declaration)) { var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(ts.getModifierFlags(anyImportSyntax) & 1) && + !ts.hasModifier(anyImportSyntax, 1) && isDeclarationVisible(anyImportSyntax.parent)) { if (shouldComputeAliasToMakeVisible) { getNodeLinks(declaration).isVisible = true; @@ -20057,8 +21453,7 @@ var ts; var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } - if (!inTypeAlias && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { + if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); @@ -20133,8 +21528,8 @@ var ts; return createTypeNodeFromObjectType(type); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isStaticMethodSymbol = !!(symbol.flags & 8192) && + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -20146,10 +21541,8 @@ var ts; } } function createTypeNodeFromObjectType(type) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - return createMappedTypeNodeFromType(type); - } + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -20677,7 +22070,7 @@ var ts; buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 1024) && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + ((flags & 65536) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); } @@ -20821,9 +22214,7 @@ var ts; if (!symbolStack) { symbolStack = []; } - var isConstructorObject = type.flags & 32768 && - getObjectFlags(type) & 16 && - type.symbol && type.symbol.flags & 32; + var isConstructorObject = type.objectFlags & 16 && type.symbol && type.symbol.flags & 32; if (isConstructorObject) { writeLiteralType(type, flags); } @@ -20838,16 +22229,16 @@ var ts; writeLiteralType(type, flags); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isStaticMethodSymbol = !!(symbol.flags & 8192) && + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { + ts.some(symbol.declarations, function (declaration) { return declaration.parent.kind === 265 || declaration.parent.kind === 234; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 4) || - (ts.contains(symbolStack, symbol)); + ts.contains(symbolStack, symbol); } } } @@ -20884,11 +22275,9 @@ var ts; return false; } function writeLiteralType(type, flags) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - writeMappedType(type); - return; - } + if (isGenericMappedType(type)) { + writeMappedType(type); + return; } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -21256,7 +22645,7 @@ var ts; case 154: case 151: case 150: - if (ts.getModifierFlags(node) & (8 | 16)) { + if (ts.hasModifier(node, 8 | 16)) { return false; } case 152: @@ -21933,8 +23322,8 @@ var ts; } } function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; @@ -22058,7 +23447,7 @@ var ts; return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + type.resolvedBaseTypes = ts.emptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { return; @@ -22100,12 +23489,7 @@ var ts; error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); return; } - if (type.resolvedBaseTypes === ts.emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } + type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type) { var outerTypeParameters = type.outerTypeParameters; @@ -22203,7 +23587,9 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var declaration = ts.findDeclaration(symbol, function (d) { return d.kind === 283 || d.kind === 231; }); + var declaration = ts.find(symbol.declarations, function (d) { + return d.kind === 283 || d.kind === 231; + }); var type = getTypeFromTypeNode(declaration.kind === 283 ? declaration.typeExpression : declaration.type); if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -22695,17 +24081,12 @@ var ts; } else { var members = emptySymbols; - var constructSignatures = ts.emptyArray; var stringIndexInfo = undefined; if (symbol.exports) { members = getExportsOfSymbol(symbol); } if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); - constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); - if (!constructSignatures.length) { - constructSignatures = getDefaultConstructSignatures(classType); - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (32768 | 131072 | 540672)) { members = ts.createSymbolTable(getNamedMembers(members)); @@ -22716,10 +24097,18 @@ var ts; } } var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; - setStructuredTypeMembers(type, members, ts.emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); if (symbol.flags & (16 | 8192)) { type.callSignatures = getSignaturesOfSymbol(symbol); } + if (symbol.flags & 32) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } } } function resolveMappedTypeMembers(type) { @@ -22802,8 +24191,7 @@ var ts; return getObjectFlags(type) & 32 && !!type.declaration.questionToken; } function isGenericMappedType(type) { - return getObjectFlags(type) & 32 && - maybeTypeOfKind(getConstraintTypeFromMappedType(type), 540672 | 262144); + return getObjectFlags(type) & 32 && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -22903,6 +24291,10 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + var transformed = getTransformedIndexedAccessType(type); + if (transformed) { + return transformed; + } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; @@ -22965,11 +24357,18 @@ var ts; return stringType; } if (t.flags & 524288) { + var transformed = getTransformedIndexedAccessType(t); + if (transformed) { + return getBaseConstraint(transformed); + } var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; } + if (isGenericMappedType(t)) { + return emptyObjectType; + } return t; } } @@ -23449,6 +24848,9 @@ var ts; } return signature.resolvedReturnType; } + function isResolvingReturnTypeOfSignature(signature) { + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3) >= 0; + } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); @@ -23517,7 +24919,7 @@ var ts; function getIndexInfoOfSymbol(symbol, kind) { var declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64), declaration); } return undefined; } @@ -23785,8 +25187,8 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; switch (declaration.kind) { case 229: case 230: @@ -24243,17 +25645,16 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { + if (!(indexType.flags & 6144) && isTypeAssignableToKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAssignableToKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); - return unknownType; } return indexInfo.type; } @@ -24285,25 +25686,68 @@ var ts; return anyType; } function getIndexedAccessForMappedType(type, indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - return unknownType; + if (accessNode) { + if (!isTypeAssignableTo(indexType, getIndexType(type))) { + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(type)); + return unknownType; + } + if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && type.declaration.readonlyToken) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + } } var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); } + function isGenericObjectType(type) { + return type.flags & 540672 ? true : + getObjectFlags(type) & 32 ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : + type.flags & 196608 ? ts.forEach(type.types, isGenericObjectType) : + false; + } + function isGenericIndexType(type) { + return type.flags & (540672 | 262144) ? true : + type.flags & 196608 ? ts.forEach(type.types, isGenericIndexType) : + false; + } + function isStringIndexOnlyType(type) { + if (type.flags & 32768 && !isGenericMappedType(type)) { + var t = resolveStructuredTypeMembers(type); + return t.properties.length === 0 && + t.callSignatures.length === 0 && t.constructSignatures.length === 0 && + t.stringIndexInfo && !t.numberIndexInfo; + } + return false; + } + function getTransformedIndexedAccessType(type) { + var objectType = type.objectType; + if (objectType.flags & 131072 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0)); + } + else { + regularTypes.push(t); + } + } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + return undefined; + } function getIndexedAccessType(objectType, indexType, accessNode) { - if (maybeTypeOfKind(indexType, 540672 | 262144) || - maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 180) || - isGenericMappedType(objectType)) { + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { return objectType; } - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } var id = objectType.id + "," + indexType.id; var type = indexedAccessTypes.get(id); if (!type) { @@ -24502,7 +25946,7 @@ var ts; var container = ts.getThisContainer(node, false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { - if (!(ts.getModifierFlags(container) & 32) && + if (!ts.hasModifier(container, 32) && (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } @@ -24649,7 +26093,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.signature, mapper.flags | 2, mapper.inferences) : + createInferenceContext(mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : mapper; } function identityMapper(type) { @@ -24913,11 +26357,13 @@ var ts; if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind === 187) { - return false; + if (node.kind !== 187) { + var parameter = ts.firstOrUndefined(node.parameters); + if (!(parameter && ts.parameterIsThisKeyword(parameter))) { + return true; + } } - var parameter = ts.firstOrUndefined(node.parameters); - return !(parameter && ts.parameterIsThisKeyword(parameter)); + return node.body.kind === 207 ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); @@ -24980,7 +26426,7 @@ var ts; return 0; } if (source.typeParameters) { - source = instantiateSignatureInContextOf(source, target); + source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var result = -1; var sourceThisType = getThisTypeOfSignature(source); @@ -25029,7 +26475,7 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(source); if (target.typePredicate) { if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(target.typePredicate)) { if (reportErrors) { @@ -25045,7 +26491,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -25054,11 +26500,13 @@ var ts; return 0; } if (source.kind === 1) { - var sourceIdentifierPredicate = source; - var targetIdentifierPredicate = target; - if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + var sourcePredicate = source; + var targetPredicate = target; + var sourceIndex = sourcePredicate.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); + var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); + if (sourceIndex !== targetIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourcePredicate.parameterName, targetPredicate.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0; @@ -25203,8 +26651,7 @@ var ts; return true; } if (source.flags & 32768 && target.flags & 32768) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); + var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1; } @@ -25317,11 +26764,21 @@ var ts; !(target.flags & 65536) && !isIntersectionConstituent && source !== globalObjectType && - getPropertiesOfType(source).length > 0 && + (getPropertiesOfType(source).length > 0 || + getSignaturesOfType(source, 0).length > 0 || + getSignaturesOfType(source, 1).length > 0) && isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { - reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + var calls = getSignaturesOfType(source, 0); + var constructs = getSignaturesOfType(source, 1); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } } return 0; } @@ -25522,7 +26979,7 @@ var ts; if (overflow) { return 0; } - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var id = getRelationKey(source, target, relation); var related = relation.get(id); if (related !== undefined) { if (reportErrors && related === 2) { @@ -25942,6 +27399,9 @@ var ts; if (sourceInfo) { return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); } + if (isGenericMappedType(source)) { + return kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + } if (isObjectLiteralType(source)) { var related = -1; if (kind === 0) { @@ -25975,8 +27435,8 @@ var ts; if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; - var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24); if (targetAccessibility === 8) { return true; } @@ -25992,6 +27452,42 @@ var ts; return false; } } + function isUnconstrainedTypeParameter(type) { + return type.flags & 16384 && !getConstraintFromTypeParameter(type); + } + function isTypeReferenceWithGenericArguments(type) { + return getObjectFlags(type) & 4 && ts.some(type.typeArguments, isUnconstrainedTypeParameter); + } + function getTypeReferenceId(type, typeParameters) { + var result = "" + type.target.id; + for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { + var t = _a[_i]; + if (isUnconstrainedTypeParameter(t)) { + var index = ts.indexOf(typeParameters, t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + } + else { + result += "-" + t.id; + } + } + return result; + } + function getRelationKey(source, target, relation) { + if (relation === identityRelation && source.id > target.id) { + var temp = source; + source = target; + target = temp; + } + if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { + var typeParameters = []; + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + } + return source.id + "," + target.id; + } function forEachProperty(prop, callback) { if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { @@ -26028,7 +27524,7 @@ var ts; var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.getModifierFlags(declaration) & 128) { + if (declaration && ts.hasModifier(declaration, 128)) { return true; } } @@ -26414,13 +27910,14 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(signature, flags, baseInferences) { + function createInferenceContext(signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); var context = mapper; context.mappedTypes = signature.typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; + context.compareTypes = compareTypes || compareTypesAssignable; return context; function mapper(t) { for (var i = 0; i < inferences.length; i++) { @@ -26508,6 +28005,19 @@ var ts; return inference.candidates && getUnionType(inference.candidates, true); } } + function isPossiblyAssignableTo(source, target) { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + if (!(targetProp.flags & (16777216 | 4194304))) { + var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (!sourceProp) { + return false; + } + } + } + return true; + } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; @@ -26668,15 +28178,17 @@ var ts; return; } } - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target); + if (isPossiblyAssignableTo(source, target) || isPossiblyAssignableTo(target, source)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target); + } } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { - var targetProp = properties_5[_i]; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -26775,7 +28287,7 @@ var ts; var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { inference.inferredType = inferredType = instantiatedConstraint; } } @@ -26823,16 +28335,6 @@ var ts; } return undefined; } - function getLeftmostIdentifierOrThis(node) { - switch (node.kind) { - case 71: - case 99: - return node; - case 179: - return getLeftmostIdentifierOrThis(node.expression); - } - return undefined; - } function getBindingElementNameText(element) { if (element.parent.kind === 174) { var name = element.propertyName || element.name; @@ -27324,7 +28826,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 84); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -27470,7 +28972,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { + if (isTypeAssignableToKind(indexType, 84)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -28156,7 +29658,7 @@ var ts; break; case 149: case 148: - if (ts.getModifierFlags(container) & 32) { + if (ts.hasModifier(container, 32)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -28247,14 +29749,14 @@ var ts; if (!isCallExpression && container.kind === 152) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } - if ((ts.getModifierFlags(container) & 32) || isCallExpression) { + if (ts.hasModifier(container, 32) || isCallExpression) { nodeCheckFlag = 512; } else { nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 151 && ts.getModifierFlags(container) & 256) { + if (container.kind === 151 && ts.hasModifier(container, 256)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } @@ -28299,7 +29801,7 @@ var ts; } else { if (ts.isClassLike(container.parent) || container.parent.kind === 178) { - if (ts.getModifierFlags(container) & 32) { + if (ts.hasModifier(container, 32)) { return container.kind === 151 || container.kind === 150 || container.kind === 153 || @@ -28489,7 +29991,7 @@ var ts; return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); - if (signature) { + if (signature && !isResolvingReturnTypeOfSignature(signature)) { return getReturnTypeOfSignature(signature); } return undefined; @@ -28593,11 +30095,11 @@ var ts; return undefined; } if (ts.isJsxAttribute(node.parent)) { - return getTypeOfPropertyOfType(attributesType, node.parent.name.escapedText); + return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); } else if (node.parent.kind === 249) { var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; + return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; } else { return attributesType; @@ -28609,7 +30111,7 @@ var ts; if (!attributesType || isTypeAny(attributesType)) { return undefined; } - return getTypeOfPropertyOfType(attributesType, attribute.name.escapedText); + return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { return attributesType; @@ -28825,10 +30327,7 @@ var ts; } } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); - } - function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || isTypeOfKind(type, kind); + return isTypeAssignableToKind(checkComputedPropertyName(name), 84); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -28840,7 +30339,9 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { + if (links.resolvedType.flags & 6144 || + !isTypeAssignableToKind(links.resolvedType, 262178 | 84 | 512) && + !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -29325,9 +30826,7 @@ var ts; return undefined; } function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (!elementType) { - elementType = checkExpression(openingLikeElement.tagName); - } + if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } if (elementType.flags & 65536) { var types = elementType.types; return getUnionType(types.map(function (type) { @@ -29422,11 +30921,12 @@ var ts; } function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { + var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; + if (!links[linkLocation]) { var elemClassType = getJsxGlobalElementClassType(); - return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); } - return links.resolvedJsxElementAttributesType; + return links[linkLocation]; } function getAllAttributesTypeFromJsxOpeningLikeElement(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -29653,9 +31153,12 @@ var ts; } var prop = getPropertyOfType(apparentType, right.escapedText); if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0); - if (stringIndexType) { - return stringIndexType; + var indexInfo = getIndexInfoOfType(apparentType, 0); + if (indexInfo && indexInfo.type) { + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + return indexInfo.type; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); @@ -29782,7 +31285,7 @@ var ts; if (prop && noUnusedIdentifiers && (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8)) { if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } @@ -30053,8 +31556,8 @@ var ts; } return undefined; } - function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature, 1); + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + var context = createInferenceContext(signature, 1, compareTypes); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); @@ -30284,7 +31787,7 @@ var ts; return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512)) { + if (isTypeAssignableToKind(nameType, 512)) { return nameType; } else { @@ -30377,9 +31880,10 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); + var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; var excludeArgument; var excludeCount = 0; - if (!isDecorator) { + if (!isDecorator && !isSingleNonGenericCandidate) { for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { if (isContextSensitive(args[i])) { if (!excludeArgument) { @@ -30471,6 +31975,17 @@ var ts; if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; candidateForTypeArgumentError = undefined; + if (isSingleNonGenericCandidate) { + var candidate = candidates[0]; + if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + return undefined; + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + candidateForArgumentError = candidate; + return undefined; + } + return candidate; + } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { @@ -30601,7 +32116,7 @@ var ts; return resolveErrorCall(node); } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { + if (valueDecl && ts.hasModifier(valueDecl, 128)) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } @@ -30637,8 +32152,8 @@ var ts; return true; } var declaration = signature.declaration; - var modifiers = ts.getModifierFlags(declaration); - if (!(modifiers & 24)) { + var modifiers = ts.getSelectedModifierFlags(declaration, 24); + if (!modifiers) { return true; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -30792,7 +32307,7 @@ var ts; && getSymbolLinks(type.symbol).inferredClassType === type; } function checkCallExpression(node) { - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); + checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 97) { return voidType; @@ -30825,7 +32340,7 @@ var ts; return getReturnTypeOfSignature(signature); } function checkImportCallExpression(node) { - checkGrammarArguments(node, node.arguments) || checkGrammarImportCallExpression(node); + checkGrammarArguments(node.arguments) || checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } @@ -30841,11 +32356,33 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeOfSymbol(esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); } } return createPromiseReturnType(node, anyType); } + function getTypeWithSyntheticDefaultImportType(type, symbol) { + if (allowSyntheticDefaultImports && type && type !== unknownType) { + var synthType = type; + if (!synthType.syntheticType) { + if (!getPropertyOfType(type, "default")) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152, "default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default", newSymbol); + var anonymousSymbol = createSymbol(2048, "__type"); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined); + anonymousSymbol.type = defaultContainingObject; + synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + } + else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } function isCommonJsRequire(node) { if (!ts.isRequireCall(node, true)) { return false; @@ -30964,15 +32501,15 @@ var ts; } } } - function assignBindingElementTypes(node) { - if (ts.isBindingPattern(node.name)) { - for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); - } - assignBindingElementTypes(element); + function assignBindingElementTypes(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 71) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + else { + assignBindingElementTypes(element.name); } } } @@ -30981,12 +32518,13 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = contextualType; - var name = ts.getNameOfDeclaration(parameter.valueDeclaration); - if (links.type === emptyObjectType && - (name.kind === 174 || name.kind === 175)) { - links.type = getTypeFromBindingPattern(name); + var decl = parameter.valueDeclaration; + if (decl.name.kind !== 71) { + if (links.type === emptyObjectType) { + links.type = getTypeFromBindingPattern(decl.name); + } + assignBindingElementTypes(decl.name); } - assignBindingElementTypes(parameter.valueDeclaration); } } function createPromiseType(promisedType) { @@ -31187,14 +32725,14 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186) { - checkGrammarForGenerator(node); - } if (checkMode === 1 && isContextSensitive(node)) { checkNodeDeferred(node); return anyFunctionType; } + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 186) { + checkGrammarForGenerator(node); + } var links = getNodeLinks(node); var type = getTypeOfSymbol(node.symbol); if (!(links.flags & 1024)) { @@ -31264,7 +32802,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { + if (!isTypeAssignableToKind(type, 84)) { error(operand, diagnostic); return false; } @@ -31352,8 +32890,13 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + if (node.operand.kind === 8) { + if (node.operator === 38) { + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + } + else if (node.operator === 37) { + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } } switch (node.operator) { case 37: @@ -31405,30 +32948,22 @@ var ts; } return false; } - function isTypeOfKind(type, kind) { - if (type.flags & kind) { + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { return true; } - if (type.flags & 65536) { - var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; - if (!isTypeOfKind(t, kind)) { - return false; - } - } - return true; + if (strict && source.flags & (1 | 1024 | 2048 | 4096)) { + return false; } - if (type.flags & 131072) { - var types = type.types; - for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { - var t = types_19[_a]; - if (isTypeOfKind(t, kind)) { - return true; - } - } - } - return false; + return (kind & 84 && isTypeAssignableTo(source, numberType)) || + (kind & 262178 && isTypeAssignableTo(source, stringType)) || + (kind & 136 && isTypeAssignableTo(source, booleanType)) || + (kind & 1024 && isTypeAssignableTo(source, voidType)) || + (kind & 8192 && isTypeAssignableTo(source, neverType)) || + (kind & 4096 && isTypeAssignableTo(source, nullType)) || + (kind & 2048 && isTypeAssignableTo(source, undefinedType)) || + (kind & 512 && isTypeAssignableTo(source, esSymbolType)) || + (kind & 16777216 && isTypeAssignableTo(source, nonPrimitiveType)); } function isConstEnumObjectType(type) { return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); @@ -31440,7 +32975,7 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (isTypeOfKind(leftType, 8190)) { + if (!isTypeAny(leftType) && isTypeAssignableToKind(leftType, 8190)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(isTypeAny(rightType) || @@ -31457,18 +32992,18 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(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)) { + if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var p = properties_6[_i]; + for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { + var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); } return sourceType; @@ -31724,24 +33259,22 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeOfKind(leftType, 1 | 262178) && !isTypeOfKind(rightType, 1 | 262178)) { + if (!isTypeAssignableToKind(leftType, 262178) && !isTypeAssignableToKind(rightType, 262178)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { + if (isTypeAssignableToKind(leftType, 84, true) && isTypeAssignableToKind(rightType, 84, true)) { resultType = numberType; } - else { - if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { - resultType = stringType; - } - else if (isTypeAny(leftType) || isTypeAny(rightType)) { - resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; - } - if (resultType && !checkForDisallowedESSymbolOperand(operator)) { - return resultType; - } + else if (isTypeAssignableToKind(leftType, 262178, true) || isTypeAssignableToKind(rightType, 262178, true)) { + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; + } + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; } if (!resultType) { reportOperatorError(); @@ -31906,13 +33439,12 @@ var ts; return getBestChoiceType(type1, type2); } function checkLiteralExpression(node) { - if (node.kind === 8) { - checkGrammarNumericLiteral(node); - } switch (node.kind) { + case 13: case 9: return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: + checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; @@ -32060,6 +33592,7 @@ var ts; return checkSuperExpression(node); case 95: return nullWideningType; + case 13: case 9: case 8: case 101: @@ -32067,8 +33600,6 @@ var ts; return checkLiteralExpression(node); case 196: return checkTemplateExpression(node); - case 13: - return stringType; case 12: return globalRegExpType; case 177: @@ -32159,7 +33690,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.getModifierFlags(node) & 92) { + if (ts.hasModifier(node, 92)) { func = ts.getContainingFunction(node); if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -32329,6 +33860,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.createUnderscoreEscapedMap(); var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { @@ -32342,7 +33880,7 @@ var ts; } } else { - var isStatic = ts.getModifierFlags(member) & 32; + var isStatic = ts.hasModifier(member, 32); var names = isStatic ? staticNames : instanceNames; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { @@ -32387,7 +33925,7 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; var memberNameNode = member.name; - var isStatic = ts.getModifierFlags(member) & 32; + var isStatic = ts.hasModifier(member, 32); if (isStatic && memberNameNode) { var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); switch (memberName) { @@ -32475,7 +34013,7 @@ var ts; function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); checkFunctionOrMethodDeclaration(node); - if (ts.getModifierFlags(node) & 128 && node.body) { + if (ts.hasModifier(node, 128) && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -32511,17 +34049,9 @@ var ts; } return ts.forEachChild(n, containsSuperCall); } - function markThisReferencesAsErrors(n) { - if (n.kind === 99) { - error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - } - else if (n.kind !== 186 && n.kind !== 228) { - ts.forEachChild(n, markThisReferencesAsErrors); - } - } function isInstancePropertyWithInitializer(n) { return n.kind === 149 && - !(ts.getModifierFlags(n) & 32) && + !ts.hasModifier(n, 32) && !!n.initializer; } var containingClassDecl = node.parent; @@ -32533,8 +34063,8 @@ var ts; if (classExtendsNull) { error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); + var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92); }); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; @@ -32577,10 +34107,12 @@ var ts; var otherKind = node.kind === 153 ? 154 : 153; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { + var nodeFlags = ts.getModifierFlags(node); + var otherFlags = ts.getModifierFlags(otherAccessor); + if ((nodeFlags & 28) !== (otherFlags & 28)) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { + if ((nodeFlags & 128) !== (otherFlags & 128)) { error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); @@ -32626,7 +34158,7 @@ var ts; function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); if (node.kind === 159 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { - grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); if (type !== unknownType) { @@ -32634,7 +34166,14 @@ var ts; ts.forEach(node.typeArguments, checkSourceElement); if (produceDiagnostics) { var symbol = getNodeLinks(node).resolvedSymbol; - var typeParameters = symbol.flags & 524288 ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; + if (!symbol) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return; + } + var typeParameters = symbol.flags & 524288 && getSymbolLinks(symbol).typeParameters; + if (!typeParameters && getObjectFlags(type) & 4) { + typeParameters = type.target.localTypeParameters; + } checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } @@ -32677,16 +34216,15 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { - var constraint = getBaseConstraintOfType(objectType); - if (constraint && getIndexInfoOfType(constraint, 1)) { - return type; - } + if (getIndexInfoOfType(getApparentType(objectType), 1) && isTypeAssignableToKind(indexType, 84)) { + return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); return type; } function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } function checkMappedType(node) { @@ -32697,7 +34235,7 @@ var ts; checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); } function isPrivateWithinAmbient(node) { - return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); + return ts.hasModifier(node, 8) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); @@ -32784,9 +34322,9 @@ var ts; (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { var reportError = (node.kind === 151 || node.kind === 150) && - (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); + ts.hasModifier(node, 32) !== ts.hasModifier(subsequentNode, 32); if (reportError) { - var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + var diagnostic = ts.hasModifier(node, 32) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -32802,7 +34340,7 @@ var ts; error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); } else { - if (ts.getModifierFlags(node) & 128) { + if (ts.hasModifier(node, 128)) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -32812,8 +34350,8 @@ var ts; } var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var current = declarations_5[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; @@ -32862,7 +34400,7 @@ var ts; }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -32930,6 +34468,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(d) { switch (d.kind) { case 230: @@ -33264,7 +34809,7 @@ var ts; if (!ts.hasDynamicName(node)) { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)); }); + var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536); }); if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); } @@ -33399,14 +34944,14 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 151 || member.kind === 149) { - if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { + if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); } } else if (member.kind === 152) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); } } @@ -33746,7 +35291,7 @@ var ts; 128 | 64 | 32; - return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); + return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); @@ -33876,7 +35421,7 @@ var ts; checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { + if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -34248,7 +35793,7 @@ var ts; var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { + if (!ts.hasModifier(member, 32) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); @@ -34345,8 +35890,8 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { var name = symbolToString(symbol); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } @@ -34355,8 +35900,8 @@ var ts; function areTypeParametersIdentical(declarations, typeParameters) { var maxTypeArgumentCount = ts.length(typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; var numTypeParameters = ts.length(declaration.typeParameters); if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { return false; @@ -34392,7 +35937,7 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (!node.name && !(ts.getModifierFlags(node) & 512)) { + if (!node.name && !ts.hasModifier(node, 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -34485,7 +36030,7 @@ var ts; var signatures = getSignaturesOfType(type, 1); if (signatures.length) { var declaration = signatures[0].declaration; - if (declaration && ts.getModifierFlags(declaration) & 8) { + if (declaration && ts.hasModifier(declaration, 8)) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); @@ -34518,7 +36063,7 @@ var ts; if (derived) { if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128))) { if (derivedClassDecl.kind === 199) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -34566,8 +36111,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { - var prop = properties_7[_a]; + for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { + var prop = properties_8[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -34821,8 +36366,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; if ((declaration.kind === 229 || (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { @@ -35037,7 +36582,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -35064,7 +36609,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (ts.getModifierFlags(node) & 1) { + if (ts.hasModifier(node, 1)) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -35092,7 +36637,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -35150,7 +36695,7 @@ var ts; } return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 71) { @@ -35197,8 +36742,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -35476,7 +37021,7 @@ var ts; return []; } var symbols = ts.createSymbolTable(); - var memberFlags = 0; + var isStatic = false; populateSymbols(); return symbolsToArray(symbols); function populateSymbols() { @@ -35498,7 +37043,7 @@ var ts; } case 229: case 230: - if (!(memberFlags & 32)) { + if (!isStatic) { copySymbols(getSymbolOfNode(location).members, meaning & 793064); } break; @@ -35512,7 +37057,7 @@ var ts; if (ts.introducesArgumentsExoticObject(location)) { copySymbol(argumentsSymbol, meaning); } - memberFlags = ts.getModifierFlags(location); + isStatic = ts.hasModifier(location, 32); location = location.parent; } copySymbols(globals, meaning); @@ -35747,12 +37292,7 @@ var ts; case 8: if (node.parent.kind === 180 && node.parent.argumentExpression === node) { var objectType = getTypeOfExpression(node.parent.expression); - if (objectType === unknownType) - return undefined; - var apparentType = getApparentType(objectType); - if (apparentType === unknownType) - return undefined; - return getPropertyOfType(apparentType, node.text); + return getPropertyOfType(objectType, node.text); } break; } @@ -35848,7 +37388,7 @@ var ts; } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return ts.getModifierFlags(node) & 32 + return ts.hasModifier(node, 32) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -36073,13 +37613,13 @@ var ts; return strictNullChecks && !isOptionalParameter(parameter) && parameter.initializer && - !(ts.getModifierFlags(parameter) & 92); + !ts.hasModifier(parameter, 92); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - !!(ts.getModifierFlags(parameter) & 92); + ts.hasModifier(parameter, 92); } function getNodeCheckFlags(node) { return getNodeLinks(node).flags; @@ -36135,22 +37675,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { + else if (isTypeAssignableToKind(type, 1024 | 6144 | 8192)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeOfKind(type, 136)) { + else if (isTypeAssignableToKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 84)) { + else if (isTypeAssignableToKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 262178)) { + else if (isTypeAssignableToKind(type, 262178)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 512)) { + else if (isTypeAssignableToKind(type, 512)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -36615,7 +38155,7 @@ var ts; node.kind !== 154) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 229 && ts.getModifierFlags(node.parent) & 128)) { + if (!(node.parent.kind === 229 && ts.hasModifier(node.parent, 128))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -36734,8 +38274,7 @@ var ts; if (list && list.hasTrailingComma) { var start = list.end - ",".length; var end = list.end; - var sourceFile = ts.getSourceFileOfNode(list[0]); - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + return grammarErrorAtPos(list[0], start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); } } function checkGrammarTypeParameterList(typeParameters, file) { @@ -36811,7 +38350,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (ts.getModifierFlags(parameter) !== 0) { + if (ts.hasModifiers(parameter)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -36845,19 +38384,18 @@ var ts; return checkGrammarForDisallowedTrailingComma(typeArguments) || checkGrammarForAtLeastOneTypeArgument(node, typeArguments); } - function checkGrammarForOmittedArgument(node, args) { + function checkGrammarForOmittedArgument(args) { if (args) { - var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; if (arg.kind === 200) { - return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } } } - function checkGrammarArguments(node, args) { - return checkGrammarForOmittedArgument(node, args); + function checkGrammarArguments(args) { + return checkGrammarForOmittedArgument(args); } function checkGrammarHeritageClause(node) { var types = node.types; @@ -36866,8 +38404,7 @@ var ts; } if (types && types.length === 0) { var listType = ts.tokenToString(node.token); - var sourceFile = ts.getSourceFileOfNode(node); - return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } return ts.forEach(types, checkGrammarExpressionWithTypeArguments); } @@ -37090,10 +38627,10 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { - return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } - else if (accessor.body && ts.getModifierFlags(accessor) & 128) { + else if (accessor.body && ts.hasModifier(accessor, 128)) { return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); } else if (accessor.typeParameters) { @@ -37146,7 +38683,7 @@ var ts; return true; } else if (node.body === undefined) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } if (ts.isClassLike(node.parent)) { @@ -37217,7 +38754,7 @@ var ts; return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } } } @@ -37237,12 +38774,12 @@ var ts; } else { var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } else if (!node.initializer) { @@ -37299,7 +38836,7 @@ var ts; return true; } if (!declarationList.declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } } function allowLetAndConstDeclarations(parent) { @@ -37345,7 +38882,8 @@ var ts; return true; } } - function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { + function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); if (!hasParseDiagnostics(sourceFile)) { diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; @@ -37360,7 +38898,7 @@ var ts; } function checkGrammarConstructorTypeParameters(node) { if (node.typeParameters) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + return grammarErrorAtPos(node, node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -37402,7 +38940,7 @@ var ts; node.kind === 244 || node.kind === 243 || node.kind === 236 || - ts.getModifierFlags(node) & (2 | 1 | 512)) { + ts.hasModifier(node, 2 | 1 | 512)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -40171,27 +41709,27 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_8 = []; + var properties_9 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_8.push(getter); + properties_9.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_8.push(setter); + properties_9.push(setter); } - properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_8, multiLine) + ts.createObjectLiteral(properties_9, multiLine) ]), firstAccessor); return ts.aggregateTransformFlags(expression); } @@ -40597,6 +42135,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 isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7; } switch (node.kind) { @@ -41929,6 +43474,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; @@ -42119,7 +43669,8 @@ var ts; ? undefined : numElements, location), false, location); } - else if (numElements !== 1 && (flattenContext.level < 1 || numElements === 0)) { + else if (numElements !== 1 && (flattenContext.level < 1 || numElements === 0) + || ts.every(elements, ts.isOmittedExpression)) { var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); } @@ -42248,6 +43799,28 @@ 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 = {})); + var ClassFacts; + (function (ClassFacts) { + ClassFacts[ClassFacts["None"] = 0] = "None"; + ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; + ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; + ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; + ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; + ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; + ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; + ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; + ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; + ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; + })(ClassFacts || (ClassFacts = {})); function transformTypeScript(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -42304,7 +43877,12 @@ var ts; if (ts.hasModifier(node, 2)) { break; } - recordEmittedDeclarationInScope(node); + if (node.name) { + recordEmittedDeclarationInScope(node); + } + else { + ts.Debug.assert(node.kind === 229 || ts.hasModifier(node, 512)); + } break; } } @@ -42718,8 +44296,8 @@ var ts; && member.initializer !== undefined; } function addInitializedPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { - var property = properties_9[_i]; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; var statement = ts.createStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); @@ -42728,8 +44306,8 @@ var ts; } function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { - var property = properties_10[_i]; + for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { + var property = properties_11[_i]; var expression = transformInitializedProperty(property, receiver); expression.startsOnNewLine = true; ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); @@ -43424,24 +45002,24 @@ var ts; && moduleKind !== ts.ModuleKind.System); } function recordEmittedDeclarationInScope(node) { - var name = node.symbol && node.symbol.escapedName; - if (name) { - if (!currentScopeFirstDeclarationsOfName) { - currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); - } - if (!currentScopeFirstDeclarationsOfName.has(name)) { - currentScopeFirstDeclarationsOfName.set(name, node); - } + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); + } + var name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); } } function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name = node.symbol && node.symbol.escapedName; - if (name) { - return currentScopeFirstDeclarationsOfName.get(name) === node; - } + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; } - return false; + return true; + } + function declaredNameInScope(node) { + ts.Debug.assertNode(node.name, ts.isIdentifier); + return node.name.escapedText; } function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ @@ -43472,7 +45050,7 @@ var ts; if (!shouldEmitModuleDeclaration(node)) { return ts.createNotEmittedStatement(node); } - ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); + ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); enableSubstitutionForNamespaceExports(); var statements = []; var emitFlags = 2; @@ -43871,6 +45449,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(); @@ -44112,6 +45694,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(); @@ -44188,6 +45774,8 @@ var ts; return visitExpressionStatement(node); case 185: return visitParenthesizedExpression(node, noDestructuringValue); + case 260: + return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); } @@ -44262,6 +45850,12 @@ var ts; function visitParenthesizedExpression(node, noDestructuringValue) { return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } function visitBinaryExpression(node, noDestructuringValue) { if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576) { return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); @@ -44708,7 +46302,7 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -45137,6 +46731,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(); @@ -45226,7 +46889,7 @@ var ts; function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 && ts.isStatement(node)) + || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 207))) || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) || isTypeScriptClassWrapper(node); } @@ -45506,9 +47169,11 @@ var ts; var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); ts.setEmitFlags(outer, 1536); - return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement + var result = ts.createParen(ts.createCall(outer, undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); + ts.addSyntheticLeadingComment(result, 3, "* @class "); + return result; } function transformClassBody(node, extendsClauseElement) { var statements = []; @@ -46093,11 +47758,12 @@ var ts; ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); if (node.transformFlags & 8388608 - && (ts.isBindingPattern(node.declarations[0].name) - || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + if (firstDeclaration) { + var lastDeclaration = ts.lastOrUndefined(declarations); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } } return declarationList; } @@ -46636,6 +48302,7 @@ var ts; function visitCatchClause(node) { var ancestorFacts = enterSubtree(4032, 0); var updated; + ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); if (ts.isBindingPattern(node.variableDeclaration.name)) { var temp = ts.createTempVariable(undefined); var newVariableDeclaration = ts.createVariableDeclaration(temp); @@ -47142,6 +48809,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"; @@ -47908,8 +49620,12 @@ var ts; } function transformAndEmitContinueStatement(node) { var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); - ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); - emitBreak(label, node); + if (label > 0) { + emitBreak(label, node); + } + else { + emitStatement(node); + } } function visitContinueStatement(node) { if (inStatementContainingYield) { @@ -47922,8 +49638,12 @@ var ts; } function transformAndEmitBreakStatement(node) { var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); - ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); - emitBreak(label, node); + if (label > 0) { + emitBreak(label, node); + } + else { + emitStatement(node); + } } function visitBreakStatement(node) { if (inStatementContainingYield) { @@ -48180,9 +49900,6 @@ var ts; var block = endBlock(); markLabel(block.endLabel); } - function isWithBlock(block) { - return block.kind === 1; - } function beginExceptionBlock() { var startLabel = defineLabel(); var endLabel = defineLabel(); @@ -48251,9 +49968,6 @@ var ts; emitNop(); exception.state = 3; } - function isExceptionBlock(block) { - return block.kind === 0; - } function beginScriptLoopBlock() { beginBlock({ kind: 3, @@ -48353,43 +50067,45 @@ var ts; return false; } function findBreakTarget(labelText) { - ts.Debug.assert(blocks !== undefined); - if (labelText) { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { - return block.breakLabel; - } - else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { - return block.breakLabel; + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } } } - } - else { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledBreak(block)) { - return block.breakLabel; + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } } } } return 0; } function findContinueTarget(labelText) { - ts.Debug.assert(blocks !== undefined); - if (labelText) { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { - return block.continueLabel; + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } } } - } - else { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledContinue(block)) { - return block.continueLabel; + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } } } } @@ -48417,7 +50133,7 @@ var ts; return literal; } function createInlineBreak(label, location) { - ts.Debug.assert(label > 0, "Invalid label: " + label); + ts.Debug.assertLessThan(0, label, "Invalid label"); return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ createInstruction(3), createLabel(label) @@ -48625,31 +50341,33 @@ var ts; for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { var block = blocks[blockIndex]; var blockAction = blockActions[blockIndex]; - if (isExceptionBlock(block)) { - if (blockAction === 0) { - if (!exceptionBlockStack) { - exceptionBlockStack = []; + switch (block.kind) { + case 0: + if (blockAction === 0) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; } - if (!statements) { - statements = []; + else if (blockAction === 1) { + currentExceptionBlock = exceptionBlockStack.pop(); } - exceptionBlockStack.push(currentExceptionBlock); - currentExceptionBlock = block; - } - else if (blockAction === 1) { - currentExceptionBlock = exceptionBlockStack.pop(); - } - } - else if (isWithBlock(block)) { - if (blockAction === 0) { - if (!withBlockStack) { - withBlockStack = []; + break; + case 1: + if (blockAction === 0) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); } - withBlockStack.push(block); - } - else if (blockAction === 1) { - withBlockStack.pop(); - } + else if (blockAction === 1) { + withBlockStack.pop(); + } + break; } } } @@ -50403,6 +52121,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); @@ -51150,14 +52880,14 @@ var ts; writer.writeLine(); } } - function emitTrailingCommentsOfPosition(pos) { + function emitTrailingCommentsOfPosition(pos, prefixSpace) { if (disabled) { return; } if (extendedDiagnostics) { ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); } - forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); if (extendedDiagnostics) { ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); } @@ -51237,15 +52967,7 @@ var ts; emitPos(commentEnd); } function isTripleSlashComment(commentPos, commentEnd) { - if (currentText.charCodeAt(commentPos + 1) === 47 && - commentPos + 2 < commentEnd && - currentText.charCodeAt(commentPos + 2) === 47) { - var textSubStr = currentText.substring(commentPos, commentEnd); - return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || - textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? - true : false; - } - return false; + return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); } } ts.createCommentWriter = createCommentWriter; @@ -51498,7 +53220,6 @@ var ts; errorNameNode = declaration.name; var format = 4 | 16384 | - 2048 | (shouldUseResolverType ? 8192 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; @@ -51512,7 +53233,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 2048 | 16384, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 16384, writer); errorNameNode = undefined; } } @@ -51742,7 +53463,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 2048 | 16384, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 16384, writer); write(";"); writeLine(); return tempVarName; @@ -52379,6 +54100,9 @@ var ts; return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); } function writeVariableStatement(node) { + if (ts.every(node.declarationList && node.declarationList.declarations, function (decl) { return decl.name && ts.isEmptyBindingPattern(decl.name); })) { + return; + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.isLet(node.declarationList)) { @@ -53757,7 +55481,9 @@ var ts; if (!(ts.getEmitFlags(node) & 131072)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = { kind: 23, pos: dotRangeStart, end: dotRangeEnd }; + var dotToken = ts.createToken(23); + dotToken.pos = dotRangeStart; + dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } @@ -53869,7 +55595,9 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + emitLeadingCommentsOfPosition(node.operatorToken.pos); writeTokenNode(node.operatorToken); + emitTrailingCommentsOfPosition(node.operatorToken.end, true); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -54056,8 +55784,19 @@ var ts; emitWithPrefix(" ", node.label); write(";"); } + function emitTokenWithComment(token, pos, contextNode) { + var node = contextNode && ts.getParseTreeNode(contextNode); + if (node && node.kind === contextNode.kind) { + pos = ts.skipTrivia(currentSourceFile.text, pos); + } + pos = writeToken(token, pos, contextNode); + if (node && node.kind === contextNode.kind) { + emitTrailingCommentsOfPosition(pos, true); + } + return pos; + } function emitReturnStatement(node) { - writeToken(96, node.pos, node); + emitTokenWithComment(96, node.pos, node); emitExpressionWithPrefix(" ", node.expression); write(";"); } @@ -54498,10 +56237,12 @@ var ts; function emitCatchClause(node) { var openParenPos = writeToken(74, node.pos); write(" "); - writeToken(19, openParenPos); - emit(node.variableDeclaration); - writeToken(20, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); - write(" "); + if (node.variableDeclaration) { + writeToken(19, openParenPos); + emit(node.variableDeclaration); + writeToken(20, node.variableDeclaration.end); + write(" "); + } emit(node.block); } function emitPropertyAssignment(node) { @@ -55187,6 +56928,76 @@ 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"] = 131328] = "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"] = 432] = "ObjectBindingPatternElements"; + 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) { @@ -55543,6 +57354,9 @@ var ts; var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } + var packageIdToSourceFile = ts.createMap(); + var sourceFileToPackageName = ts.createMap(); + var redirectTargetsSet = ts.createMap(); var filesByName = ts.createMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; var structuralIsReused = tryReuseStructureFromOldProgram(); @@ -55599,6 +57413,8 @@ var ts; isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsSet: redirectTargetsSet, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -55742,17 +57558,51 @@ var ts; var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2; - for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { - var oldSourceFile = _a[_i]; + var oldSourceFiles = oldProgram.getSourceFiles(); + var SeenPackageName; + (function (SeenPackageName) { + SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; + SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; + })(SeenPackageName || (SeenPackageName = {})); + var seenPackageNames = ts.createMap(); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { return oldProgram.structureIsReused = 0; } + ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + var fileChanged = void 0; + if (oldSourceFile.redirectInfo) { + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + return oldProgram.structureIsReused = 0; + } + fileChanged = false; + newSourceFile = oldSourceFile; + } + else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + if (newSourceFile !== oldSourceFile) { + return oldProgram.structureIsReused = 0; + } + fileChanged = false; + } + else { + fileChanged = newSourceFile !== oldSourceFile; + } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); - if (oldSourceFile !== newSourceFile) { + var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== undefined) { + var prevKind = seenPackageNames.get(packageName); + var newKind = fileChanged ? 1 : 0; + if ((prevKind !== undefined && newKind === 1) || prevKind === 1) { + return oldProgram.structureIsReused = 0; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { oldProgram.structureIsReused = 1; } @@ -55780,8 +57630,8 @@ var ts; 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; + for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { + var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); @@ -55815,8 +57665,8 @@ var ts; if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { return oldProgram.structureIsReused = 1; } - for (var _d = 0, _e = oldProgram.getMissingFilePaths(); _d < _e.length; _d++) { - var p = _e[_d]; + for (var _c = 0, _d = oldProgram.getMissingFilePaths(); _c < _d.length; _c++) { + var p = _d[_c]; filesByName.set(p, undefined); } for (var i = 0; i < newSourceFiles.length; i++) { @@ -55824,11 +57674,13 @@ var ts; } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _f = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _f < modifiedSourceFiles_2.length; _f++) { - var modifiedFile = modifiedSourceFiles_2[_f]; + for (var _e = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _e < modifiedSourceFiles_2.length; _e++) { + var modifiedFile = modifiedSourceFiles_2[_e]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsSet = oldProgram.redirectTargetsSet; return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { @@ -56307,7 +58159,7 @@ var ts; } } function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, undefined); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -56324,7 +58176,24 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + var redirect = Object.create(redirectTarget); + redirect.fileName = fileName; + redirect.path = path; + redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + Object.defineProperties(redirect, { + id: { + get: function () { return this.redirectInfo.redirectTarget.id; }, + set: function (value) { this.redirectInfo.redirectTarget.id = value; }, + }, + symbol: { + get: function () { return this.redirectInfo.redirectTarget.symbol; }, + set: function (value) { this.redirectInfo.redirectTarget.symbol = value; }, + }, + }); + return redirect; + } + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) { if (filesByName.has(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { @@ -56355,6 +58224,22 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + if (packageId) { + var packageIdKey = packageId.name + "@" + packageId.version; + var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); + redirectTargetsSet.set(fileFromPackageId.path, true); + filesByName.set(path, dupFile); + sourceFileToPackageName.set(path, packageId.name); + files.push(dupFile); + return dupFile; + } + else if (file) { + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageId.name); + } + } filesByName.set(path, file); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); @@ -56476,7 +58361,7 @@ var ts; else if (shouldAddFile) { var path = toPath(resolvedFileName); var pos = ts.skipTrivia(file.text, file.imports[i].pos); - findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end); + findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end, resolution.packageId); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -57155,6 +59040,12 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, { name: "sourceRoot", type: "string", @@ -57766,7 +59657,7 @@ var ts; var text = valueExpression.text; if (option && typeof option.type !== "string") { var customOption = option; - if (!customOption.type.has(text)) { + if (!customOption.type.has(text.toLowerCase())) { errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); } } @@ -58017,12 +59908,10 @@ var ts; } } else { - var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - specs.push(outDir); + excludeSpecs = [outDir]; } - excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; @@ -58273,7 +60162,7 @@ var ts; return value; } else if (typeof option.type !== "string") { - return option.type.get(value); + return option.type.get(typeof value === "string" ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -58348,23 +60237,13 @@ var ts; }; } function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { - var validSpecs = []; - for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { - var spec = specs_1[_i]; - if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); } - else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); - } - else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); - } - else { - validSpecs.push(spec); - } - } - return validSpecs; + return diag === undefined; + }); function createDiagnostic(message, spec) { if (jsonSourceFile && jsonSourceFile.jsonObject) { for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { @@ -58382,6 +60261,17 @@ var ts; return ts.createCompilerDiagnostic(message, spec); } } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); @@ -59004,6 +60894,7 @@ var ts; return; } })(ts || (ts = {})); +ts.setStackTraceLimit(); if (ts.Debug.isDebugging) { ts.Debug.enableDebugInfo(); } @@ -59011,3 +60902,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 e5ab892428..c18f6507ca 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -508,11 +508,11 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 2048] = "UseTypeAliasValue"; TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -759,6 +759,12 @@ var ts; InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); var SpecialPropertyAssignmentKind; (function (SpecialPropertyAssignmentKind) { SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; @@ -1155,16 +1161,10 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.5"; + ts.versionMajorMinor = "2.6"; ts.version = ts.versionMajorMinor + ".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() { @@ -1452,10 +1452,9 @@ var ts; ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (f(item)) { - array[outIndex] = item; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; outIndex++; } } @@ -1501,8 +1500,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1572,11 +1571,13 @@ var ts; ts.sameFlatMap = sameFlatMap; function mapDefined(array, mapFn) { var result = []; - for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); - if (mapped !== undefined) { - result.push(mapped); + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } } } return result; @@ -1644,8 +1645,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; if (predicate(v)) { return true; } @@ -1670,8 +1671,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var item = array_6[_i]; + loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -1759,8 +1760,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var v = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -2020,8 +2021,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var value = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -2181,11 +2182,11 @@ var ts; ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { var end = start + length; - Debug.assert(start >= 0, "start must be non-negative, is " + start); - Debug.assert(length >= 0, "length must be non-negative, is " + length); + Debug.assertGreaterThanOrEqual(start, 0); + Debug.assertGreaterThanOrEqual(length, 0); if (file) { - Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); - Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + Debug.assertLessThanOrEqual(start, file.text.length); + Debug.assertLessThanOrEqual(end, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -2394,19 +2395,23 @@ var ts; return normalized; } function normalizePath(path) { + return normalizePathAndParts(path).path; + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { path = normalizeSlashes(path); var rootLength = getRootLength(path); var root = path.substr(0, rootLength); - var normalized = getNormalizedParts(path, rootLength); - if (normalized.length) { - var joinedParts = root + normalized.join(ts.directorySeparator); - return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts; + var parts = getNormalizedParts(path, rootLength); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; } else { - return root; + return { path: root, parts: parts }; } } - ts.normalizePath = normalizePath; + ts.normalizePathAndParts = normalizePathAndParts; function pathEndsWithDirectorySeparator(path) { return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; } @@ -2669,8 +2674,28 @@ var ts; ts.fileExtensionIsOneOf = fileExtensionIsOneOf; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; - var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; - var singleAsteriskRegexFragmentOther = "[^/]*"; + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; function getRegularExpressionForWildcard(specs, basePath, usage) { var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); if (!patterns || !patterns.length) { @@ -2685,18 +2710,16 @@ var ts; if (specs === undefined || specs.length === 0) { return undefined; } - var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; - var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; - var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; return flatMap(specs, function (spec) { - return spec && getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } function isImplicitGlob(lastPathComponent) { return !/[.*?]/.test(lastPathComponent); } ts.isImplicitGlob = isImplicitGlob; - function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; @@ -2728,16 +2751,24 @@ var ts; subpattern += ts.directorySeparator; } if (usage !== "exclude") { + var componentPattern = ""; if (component.charCodeAt(0) === 42) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; component = component.substr(1); } else if (component.charCodeAt(0) === 63) { - subpattern += "[^./]"; + componentPattern += "[^./]"; component = component.substr(1); } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } hasWrittenComponent = true; } @@ -2747,12 +2778,6 @@ var ts; } return subpattern; } - function replaceWildCardCharacterFiles(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); - } - function replaceWildCardCharacterOther(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); - } function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } @@ -2889,14 +2914,7 @@ var ts; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = allSupportedExtensions.slice(0); - for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { - var extInfo = extraFileExtensions_1[_i]; - if (extensions.indexOf(extInfo.extension) === -1) { - extensions.push(extInfo.extension); - } - } - return extensions; + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -3038,12 +3056,37 @@ var ts; function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { if (verboseDebugInfo) { - message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); } fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; function fail(message, stackCrawlMark) { debugger; var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); @@ -3178,6 +3221,10 @@ var ts; Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; function tryGetExtensionFromPath(path) { return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } @@ -3189,6 +3236,12 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; var FileWatcherEventKind; (function (FileWatcherEventKind) { FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; @@ -3238,7 +3291,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -4064,6 +4117,8 @@ var ts; Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4251,6 +4306,7 @@ var ts; Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -4504,6 +4560,8 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), + Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), }; })(ts || (ts = {})); var ts; @@ -4516,6 +4574,12 @@ var ts; return compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(undefined, r); + } var Extensions; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; @@ -4531,12 +4595,11 @@ var ts; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } - function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); + function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { if (!ts.hasProperty(jsonContent, fieldName)) { @@ -4630,7 +4693,9 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - resolved = realpath(resolved, host, traceEnabled); + if (!options.preserveSymlinks) { + resolved = realPath(resolved, host, traceEnabled); + } if (traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); } @@ -4931,7 +4996,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension }; + return { path: path_1, extension: extension, packageId: undefined }; } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -4952,7 +5017,7 @@ var ts; 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(", ")); + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } @@ -4978,16 +5043,22 @@ var ts; trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); - return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks) { + resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + } + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); - return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } } } - function realpath(path, host, traceEnabled) { + function realPath(path, host, traceEnabled) { if (!host.realpath) { return path; } @@ -5013,7 +5084,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return resolvedFromFile; + return noPackageId(resolvedFromFile); } } if (!onlyRecordFailures) { @@ -5031,6 +5102,9 @@ var ts; return !host.directoryExists || host.directoryExists(directoryName); } ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + } function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -5060,9 +5134,9 @@ var ts; case Extensions.JavaScript: return tryExtension(".js") || tryExtension(".jsx"); } - function tryExtension(extension) { - var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, extension: extension }; + function tryExtension(ext) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, ext: ext }; } } function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { @@ -5085,12 +5159,20 @@ var ts; function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + var packageId; if (considerPackageJson) { var packageJsonPath = pathToPackageJson(candidate); if (directoryExists && state.host.fileExists(packageJsonPath)) { - var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var jsonContent = readJson(packageJsonPath, state.host); + if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { + packageId = { name: jsonContent.name, version: jsonContent.version }; + } + var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); if (fromPackageJson) { - return fromPackageJson; + return withPackageId(packageId, fromPackageJson); } } else { @@ -5100,13 +5182,10 @@ var ts; failedLookupLocations.push(packageJsonPath); } } - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } - function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); if (!file) { return undefined; } @@ -5122,11 +5201,15 @@ var ts; } } var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + if (result) { + ts.Debug.assert(result.packageId === undefined); + return { path: result.path, ext: result.extension }; + } } function resolvedIfExtensionMatches(extensions, path) { - var extension = ts.tryGetExtensionFromPath(path); - return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; } function extensionIsOk(extensions, extension) { switch (extensions) { @@ -5143,7 +5226,7 @@ var ts; } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { @@ -5217,7 +5300,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); } - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -5228,7 +5311,7 @@ var ts; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -5240,7 +5323,7 @@ var ts; return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, false, state)); }); if (resolved_3) { return resolved_3; @@ -5251,7 +5334,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, false, state)); } } } @@ -5302,19 +5385,6 @@ var ts; return undefined; } ts.getDeclarationOfKind = getDeclarationOfKind; - function findDeclaration(symbol, predicate) { - var declarations = symbol.declarations; - if (declarations) { - for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { - var declaration = declarations_2[_i]; - if (predicate(declaration)) { - return declaration; - } - } - } - return undefined; - } - ts.findDeclaration = findDeclaration; var stringWriter = createSingleLineStringWriter(); var stringWriterAcquired = false; function createSingleLineStringWriter() { @@ -5377,9 +5447,13 @@ var ts; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && - oldResolution.resolvedFileName === newResolution.resolvedFileName; + oldResolution.resolvedFileName === newResolution.resolvedFileName && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function packageIdIsEqual(a, b) { + return a === b || a && b && a.name === b.name && a.version === b.version; + } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -5444,14 +5518,6 @@ var ts; return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; } ts.nodePosToString = nodePosToString; - function getStartPosOfNode(node) { - return node.pos; - } - ts.getStartPosOfNode = getStartPosOfNode; - function isDefined(value) { - return value !== undefined; - } - ts.isDefined = isDefined; function getEndLinePosition(line, sourceFile) { ts.Debug.assert(line >= 0); var lineStarts = ts.getLineStarts(sourceFile); @@ -5482,6 +5548,25 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + if (text.charCodeAt(commentPos + 1) === 47 && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, comment) { + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 33; + } + ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { if (nodeIsMissing(node)) { return node.pos; @@ -5538,15 +5623,20 @@ var ts; var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return '"' + escapeText(node.text) + '"'; + if (node.singleQuote) { + return "'" + escapeText(node.text, 39) + "'"; + } + else { + return '"' + escapeText(node.text, 34) + '"'; + } case 13: - return "`" + escapeText(node.text) + "`"; + return "`" + escapeText(node.text, 96) + "`"; case 14: - return "`" + escapeText(node.text) + "${"; + return "`" + escapeText(node.text, 96) + "${"; case 15: - return "}" + escapeText(node.text) + "${"; + return "}" + escapeText(node.text, 96) + "${"; case 16: - return "}" + escapeText(node.text) + "`"; + return "}" + escapeText(node.text, 96) + "`"; case 8: return node.text; } @@ -5798,13 +5888,9 @@ var ts; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); + return node.kind !== 10 ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; - function getLeadingCommentRangesOfNodeFromText(node, text) { - return ts.getLeadingCommentRanges(text, node.pos); - } - ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; function getJSDocCommentRanges(node, text) { var commentRanges = (node.kind === 146 || node.kind === 145 || @@ -5812,7 +5898,7 @@ var ts; node.kind === 187 || node.kind === 185) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : - getLeadingCommentRangesOfNodeFromText(node, text); + ts.getLeadingCommentRanges(text, node.pos); return ts.filter(commentRanges, function (comment) { return text.charCodeAt(comment.pos + 1) === 42 && text.charCodeAt(comment.pos + 2) === 42 && @@ -5821,8 +5907,9 @@ var ts; } ts.getJSDocCommentRanges = getJSDocCommentRanges; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; - ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { if (158 <= node.kind && node.kind <= 173) { return true; @@ -6049,21 +6136,11 @@ var ts; } ts.getPropertyAssignment = getPropertyAssignment; function getContainingFunction(node) { - while (true) { - node = node.parent; - if (!node || ts.isFunctionLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isFunctionLike); } ts.getContainingFunction = getContainingFunction; function getContainingClass(node) { - while (true) { - node = node.parent; - if (!node || ts.isClassLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isClassLike); } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { @@ -6873,14 +6950,14 @@ var ts; ts.getAncestor = getAncestor; function getFileReferenceFromReferencePath(comment, commentRange) { var simpleReferenceRegEx = /^\/\/\/\s*/gim; + var isNoDefaultLibRegEx = new RegExp(defaultLibReferenceRegEx.source, "gim"); if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); - var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); + var refLibResult = !refMatchResult && fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); var match = refMatchResult || refLibResult; if (match) { var pos = commentRange.pos + match[1].length + match[2].length; @@ -7069,10 +7146,6 @@ var ts; return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } ts.getOriginalSourceFile = getOriginalSourceFile; - function getOriginalSourceFiles(sourceFiles) { - return ts.sameMap(sourceFiles, getOriginalSourceFile); - } - ts.getOriginalSourceFiles = getOriginalSourceFiles; var Associativity; (function (Associativity) { Associativity[Associativity["Left"] = 0] = "Left"; @@ -7311,7 +7384,9 @@ var ts; } } ts.createDiagnosticCollection = createDiagnosticCollection; - var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\0": "\\0", "\t": "\\t", @@ -7322,11 +7397,16 @@ var ts; "\n": "\\n", "\\": "\\\\", "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" }); - function escapeString(s) { + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; return s.replace(escapedCharsRegExp, getReplacement); } ts.escapeString = escapeString; @@ -7344,8 +7424,8 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiString(s) { - s = escapeString(s); + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; @@ -7686,7 +7766,7 @@ var ts; var currentDetachedCommentInfo; if (removeComments) { if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); } } else { @@ -7718,9 +7798,8 @@ var ts; } } return currentDetachedCommentInfo; - function isPinnedComment(comment) { - return text.charCodeAt(comment.pos + 1) === 42 && - text.charCodeAt(comment.pos + 2) === 33; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment); } } ts.emitDetachedComments = emitDetachedComments; @@ -7791,9 +7870,13 @@ var ts; } ts.hasModifiers = hasModifiers; function hasModifier(node, flags) { - return (getModifierFlags(node) & flags) !== 0; + return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; function getModifierFlags(node) { if (node.modifierFlagsCache & 536870912) { return node.modifierFlagsCache & ~536870912; @@ -7869,21 +7952,6 @@ var ts; return false; } ts.isDestructuringAssignment = isDestructuringAssignment; - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 71) { - return true; - } - else if (ts.isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } - } function isExpressionWithTypeArgumentsInClassExtendsClause(node) { return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } @@ -7996,72 +8064,6 @@ var ts; return carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; - function isSimpleExpression(node) { - return isSimpleExpressionWorker(node, 0); - } - ts.isSimpleExpression = isSimpleExpression; - function isSimpleExpressionWorker(node, depth) { - if (depth <= 5) { - var kind = node.kind; - if (kind === 9 - || kind === 8 - || kind === 12 - || kind === 13 - || kind === 71 - || kind === 99 - || kind === 97 - || kind === 101 - || kind === 86 - || kind === 95) { - return true; - } - else if (kind === 179) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 180) { - return isSimpleExpressionWorker(node.expression, depth + 1) - && isSimpleExpressionWorker(node.argumentExpression, depth + 1); - } - else if (kind === 192 - || kind === 193) { - return isSimpleExpressionWorker(node.operand, depth + 1); - } - else if (kind === 194) { - return node.operatorToken.kind !== 40 - && isSimpleExpressionWorker(node.left, depth + 1) - && isSimpleExpressionWorker(node.right, depth + 1); - } - else if (kind === 195) { - return isSimpleExpressionWorker(node.condition, depth + 1) - && isSimpleExpressionWorker(node.whenTrue, depth + 1) - && isSimpleExpressionWorker(node.whenFalse, depth + 1); - } - else if (kind === 190 - || kind === 189 - || kind === 188) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 177) { - return node.elements.length === 0; - } - else if (kind === 178) { - return node.properties.length === 0; - } - else if (kind === 181) { - if (!isSimpleExpressionWorker(node.expression, depth + 1)) { - return false; - } - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (!isSimpleExpressionWorker(argument, depth + 1)) { - return false; - } - } - return true; - } - } - return false; - } function formatEnum(value, enumObject, isFlags) { if (value === void 0) { value = 0; } var members = getEnumMembers(enumObject); @@ -8130,18 +8132,6 @@ var ts; return formatEnum(flags, ts.ObjectFlags, true); } ts.formatObjectFlags = formatObjectFlags; - function getRangePos(range) { - return range ? range.pos : -1; - } - ts.getRangePos = getRangePos; - function getRangeEnd(range) { - return range ? range.end : -1; - } - ts.getRangeEnd = getRangeEnd; - function movePos(pos, value) { - return ts.positionIsSynthesized(pos) ? -1 : pos + value; - } - ts.movePos = movePos; function createRange(pos, end) { return { pos: pos, end: end }; } @@ -8170,14 +8160,6 @@ var ts; return range.pos === range.end; } ts.isCollapsedRange = isCollapsedRange; - function collapseRangeToStart(range) { - return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); - } - ts.collapseRangeToStart = collapseRangeToStart; - function collapseRangeToEnd(range) { - return isCollapsedRange(range) ? range : moveRangePos(range, range.end); - } - ts.collapseRangeToEnd = collapseRangeToEnd; function createTokenRange(pos, token) { return createRange(pos, pos + ts.tokenToString(token).length); } @@ -8230,22 +8212,6 @@ var ts; function isInitializedVariable(node) { return node.initializer !== undefined; } - function isMergedWithClass(node) { - if (node.symbol) { - for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 229 && declaration !== node) { - return true; - } - } - } - return false; - } - ts.isMergedWithClass = isMergedWithClass; - function isFirstDeclarationOfKind(node, kind) { - return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; - } - ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; function isWatchSet(options) { return options.watch && options.hasOwnProperty("watch"); } @@ -8446,6 +8412,20 @@ var ts; return ts.hasModifier(node, 92) && node.parent.kind === 152 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { while (node && (node.kind === 176 || ts.isBindingPattern(node))) { node = node.parent; @@ -9526,6 +9506,18 @@ var ts; return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 193: + return true; + case 192: + return expr.operator === 43 || + expr.operator === 44; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; function isExpressionKind(kind) { return kind === 195 || kind === 197 @@ -9710,9 +9702,19 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 207; + || isBlockStatement(node); } ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 207) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 224 || node.parent.kind === 260) { + return false; + } + } + return !ts.isFunctionBlock(node); + } function isModuleReference(node) { var kind = node.kind; return kind === 248 @@ -13217,11 +13219,31 @@ var ts; var node = parseTokenNode(); return token() === 23 ? undefined : node; } - function parseLiteralTypeNode() { + function parseLiteralTypeNode(negative) { var node = createNode(173); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(192); + unaryMinusExpression.operator = 38; + nextToken(); + } + var expression; + switch (token()) { + case 9: + case 8: + expression = parseLiteralLikeNode(token()); + break; + case 101: + case 86: + expression = parseTokenNode(); + } + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); } function nextTokenIsNumericLiteral() { return nextToken() === 8; @@ -13253,7 +13275,7 @@ var ts; case 86: return parseLiteralTypeNode(); case 38: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(true) : parseTypeReference(); case 105: case 95: return parseTokenNode(); @@ -13302,6 +13324,7 @@ var ts; case 101: case 86: case 134: + case 39: return true; case 38: return lookAhead(nextTokenIsNumericLiteral); @@ -13620,7 +13643,7 @@ var ts; if (!arrowFunction) { return undefined; } - var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); + var isAsync = ts.hasModifier(arrowFunction, 256); var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 36 || lastToken === 17) @@ -13736,7 +13759,7 @@ var ts; function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(187); node.modifiers = parseModifiersForArrowFunction(); - var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); if (!node.parameters) { return undefined; @@ -14469,7 +14492,7 @@ var ts; parseExpected(89); node.asteriskToken = parseOptionalToken(39); var isGenerator = node.asteriskToken ? 1 : 0; - var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -14694,10 +14717,13 @@ var ts; function parseCatchClause() { var result = createNode(260); parseExpected(74); - if (parseExpected(19)) { + if (parseOptional(19)) { result.variableDeclaration = parseVariableDeclaration(); + parseExpected(20); + } + else { + result.variableDeclaration = undefined; } - parseExpected(20); result.block = parseBlock(false); return finishNode(result); } @@ -16429,8 +16455,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -16502,8 +16528,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -17275,40 +17301,23 @@ var ts; return antecedent; } setFlowNodeReferenced(antecedent); - return { - flags: flags, - expression: expression, - antecedent: antecedent - }; + return { flags: flags, expression: expression, antecedent: antecedent }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); - return { - flags: 128, - switchStatement: switchStatement, - clauseStart: clauseStart, - clauseEnd: clauseEnd, - antecedent: antecedent - }; + return { flags: 128, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { setFlowNodeReferenced(antecedent); - return { - flags: 16, - antecedent: antecedent, - node: node - }; + return { flags: 16, antecedent: antecedent, node: node }; } function createFlowArrayMutation(antecedent, node) { setFlowNodeReferenced(antecedent); - return { - flags: 256, - antecedent: antecedent, - node: node - }; + var res = { flags: 256, antecedent: antecedent, node: node }; + return res; } function finishFlowLabel(flow) { var antecedents = flow.antecedents; @@ -18776,7 +18785,6 @@ var ts; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); var name = node.name; var initializer = node.initializer; var dotDotDotToken = node.dotDotDotToken; @@ -18786,7 +18794,7 @@ var ts; || ts.isThisIdentifier(name)) { transformFlags |= 3; } - if (modifierFlags & 92) { + if (ts.hasModifier(node, 92)) { transformFlags |= 3 | 262144; } if (subtreeFlags & 1048576) { @@ -18815,8 +18823,7 @@ var ts; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 2) { + if (ts.hasModifier(node, 2)) { transformFlags = 3; } else { @@ -18862,7 +18869,10 @@ var ts; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + if (!node.variableDeclaration) { + transformFlags |= 8; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; @@ -19026,9 +19036,8 @@ var ts; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; - var modifierFlags = ts.getModifierFlags(node); var declarationListTransformFlags = node.declarationList.transformFlags; - if (modifierFlags & 2) { + if (ts.hasModifier(node, 2)) { transformFlags = 3; } else { @@ -19327,6 +19336,167 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = ts.createMap(); + var visitedSymbols = ts.createMap(); + return { + walkType: function (type) { + visitedTypes.clear(); + visitedSymbols.clear(); + visitType(type); + return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + }, + walkSymbol: function (symbol) { + visitedTypes.clear(); + visitedSymbols.clear(); + visitSymbol(symbol); + return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + }, + }; + function visitType(type) { + if (!type) { + return; + } + var typeIdString = type.id.toString(); + if (visitedTypes.has(typeIdString)) { + return; + } + visitedTypes.set(typeIdString, type); + var shouldBail = visitSymbol(type.symbol); + if (shouldBail) + return; + if (type.flags & 32768) { + var objectType = type; + var objectFlags = objectType.objectFlags; + if (objectFlags & 4) { + visitTypeReference(type); + } + if (objectFlags & 32) { + visitMappedType(type); + } + if (objectFlags & (1 | 2)) { + visitInterfaceType(type); + } + if (objectFlags & (8 | 16)) { + visitObjectType(objectType); + } + } + if (type.flags & 16384) { + visitTypeParameter(type); + } + if (type.flags & 196608) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 262144) { + visitIndexType(type); + } + if (type.flags & 524288) { + visitIndexedAccessType(type); + } + } + function visitTypeList(types) { + if (!types) { + return; + } + for (var i = 0; i < types.length; i++) { + visitType(types[i]); + } + } + function visitTypeReference(type) { + visitType(type.target); + visitTypeList(type.typeArguments); + } + function visitTypeParameter(type) { + visitType(getConstraintFromTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + visitTypeList(type.types); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + if (signature.typePredicate) { + visitType(signature.typePredicate.type); + } + visitTypeList(signature.typeParameters); + for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + visitTypeList(interfaceT.typeParameters); + visitTypeList(getBaseTypes(interfaceT)); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + var stringIndexType = getIndexTypeOfStructuredType(type, 0); + visitType(stringIndexType); + var numberIndexType = getIndexTypeOfStructuredType(type, 1); + visitType(numberIndexType); + var resolved = resolveStructuredTypeMembers(type); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + visitSignature(signature); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + visitSignature(signature); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return; + } + var symbolIdString = ts.getSymbolId(symbol).toString(); + if (visitedSymbols.has(symbolIdString)) { + return; + } + visitedSymbols.set(symbolIdString, symbol); + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); + if (symbol.flags & 1952) { + symbol.exports.forEach(visitSymbol); + } + ts.forEach(symbol.declarations, function (d) { + if (d.type && d.type.kind === 162) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); +var ts; (function (ts) { var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; @@ -19437,6 +19607,9 @@ var ts; node = ts.getParseTreeNode(node, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, + getExportSymbolOfSymbol: function (symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, getTypeAtLocation: function (node) { node = ts.getParseTreeNode(node); return node ? getTypeOfNode(node) : unknownType; @@ -19499,6 +19672,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); @@ -19519,11 +19693,10 @@ var ts; getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, getBaseConstraintOfType: getBaseConstraintOfType, - getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, - resolveNameAtLocation: function (location, name, meaning) { - location = ts.getParseTreeNode(location); - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, ts.escapeLeadingUnderscores(name)); + resolveName: function (name, location, meaning) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined); }, + getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -20006,7 +20179,10 @@ var ts; } return true; } - if (usage.parent.kind === 246) { + if (usage.parent.kind === 246 || (usage.parent.kind === 243 && usage.parent.isExportEquals)) { + return true; + } + if (usage.kind === 243 && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -20036,13 +20212,13 @@ var ts; current.parent.kind === 149 && current.parent.initializer === current; if (initializerOfProperty) { - if (ts.getModifierFlags(current.parent) & 32) { + if (ts.hasModifier(current.parent, 32)) { if (declaration.kind === 151) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 149 && !(ts.getModifierFlags(declaration) & 32); + var isDeclarationInstanceProperty = declaration.kind === 149 && !ts.hasModifier(declaration, 32); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -20122,7 +20298,7 @@ var ts; break; case 149: case 148: - if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 107455)) { @@ -20139,7 +20315,7 @@ var ts; result = undefined; break; } - if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { + if (lastLocation && ts.hasModifier(lastLocation, 32)) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; } @@ -20153,6 +20329,17 @@ var ts; } } break; + case 201: + if (lastLocation === location.expression && location.parent.token === 85) { + var container = location.parent.parent; + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 793064))) { + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return undefined; + } + } + break; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { @@ -20199,7 +20386,7 @@ var ts; lastLocation = location; location = location.parent; } - if (result && nameNotFoundMessage && noUnusedIdentifiers) { + if (result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { result.isReferenced = true; } if (!result) { @@ -20280,7 +20467,7 @@ var ts; error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); return true; } - if (location === container && !(ts.getModifierFlags(location) & 32)) { + if (location === container && !ts.hasModifier(location, 32)) { var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); @@ -20666,7 +20853,6 @@ var ts; if (ambientModule) { return ambientModule; } - var isRelative = ts.isExternalModuleNameRelative(moduleReference); var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); @@ -20685,7 +20871,7 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule && resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -21020,6 +21206,10 @@ var ts; } return false; } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064, false); + return access.accessibility === 0; + } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; @@ -21075,7 +21265,7 @@ var ts; if (!isDeclarationVisible(declaration)) { var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(ts.getModifierFlags(anyImportSyntax) & 1) && + !ts.hasModifier(anyImportSyntax, 1) && isDeclarationVisible(anyImportSyntax.parent)) { if (shouldComputeAliasToMakeVisible) { getNodeLinks(declaration).isVisible = true; @@ -21273,8 +21463,7 @@ var ts; var name = symbolToName(type.symbol, context, 793064, false); return ts.createTypeReferenceNode(name, undefined); } - if (!inTypeAlias && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { + if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); @@ -21349,8 +21538,8 @@ var ts; return createTypeNodeFromObjectType(type); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isStaticMethodSymbol = !!(symbol.flags & 8192) && + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -21362,10 +21551,8 @@ var ts; } } function createTypeNodeFromObjectType(type) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - return createMappedTypeNodeFromType(type); - } + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -21893,7 +22080,7 @@ var ts; buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 1024) && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + ((flags & 65536) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); } @@ -22037,9 +22224,7 @@ var ts; if (!symbolStack) { symbolStack = []; } - var isConstructorObject = type.flags & 32768 && - getObjectFlags(type) & 16 && - type.symbol && type.symbol.flags & 32; + var isConstructorObject = type.objectFlags & 16 && type.symbol && type.symbol.flags & 32; if (isConstructorObject) { writeLiteralType(type, flags); } @@ -22054,16 +22239,16 @@ var ts; writeLiteralType(type, flags); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isStaticMethodSymbol = !!(symbol.flags & 8192) && + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { + ts.some(symbol.declarations, function (declaration) { return declaration.parent.kind === 265 || declaration.parent.kind === 234; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 4) || - (ts.contains(symbolStack, symbol)); + ts.contains(symbolStack, symbol); } } } @@ -22100,11 +22285,9 @@ var ts; return false; } function writeLiteralType(type, flags) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - writeMappedType(type); - return; - } + if (isGenericMappedType(type)) { + writeMappedType(type); + return; } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -22472,7 +22655,7 @@ var ts; case 154: case 151: case 150: - if (ts.getModifierFlags(node) & (8 | 16)) { + if (ts.hasModifier(node, 8 | 16)) { return false; } case 152: @@ -23149,8 +23332,8 @@ var ts; } } function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; @@ -23274,7 +23457,7 @@ var ts; return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + type.resolvedBaseTypes = ts.emptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { return; @@ -23316,12 +23499,7 @@ var ts; error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); return; } - if (type.resolvedBaseTypes === ts.emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } + type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type) { var outerTypeParameters = type.outerTypeParameters; @@ -23419,7 +23597,9 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var declaration = ts.findDeclaration(symbol, function (d) { return d.kind === 283 || d.kind === 231; }); + var declaration = ts.find(symbol.declarations, function (d) { + return d.kind === 283 || d.kind === 231; + }); var type = getTypeFromTypeNode(declaration.kind === 283 ? declaration.typeExpression : declaration.type); if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -23911,17 +24091,12 @@ var ts; } else { var members = emptySymbols; - var constructSignatures = ts.emptyArray; var stringIndexInfo = undefined; if (symbol.exports) { members = getExportsOfSymbol(symbol); } if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); - constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); - if (!constructSignatures.length) { - constructSignatures = getDefaultConstructSignatures(classType); - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (32768 | 131072 | 540672)) { members = ts.createSymbolTable(getNamedMembers(members)); @@ -23932,10 +24107,18 @@ var ts; } } var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; - setStructuredTypeMembers(type, members, ts.emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); if (symbol.flags & (16 | 8192)) { type.callSignatures = getSignaturesOfSymbol(symbol); } + if (symbol.flags & 32) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } } } function resolveMappedTypeMembers(type) { @@ -24018,8 +24201,7 @@ var ts; return getObjectFlags(type) & 32 && !!type.declaration.questionToken; } function isGenericMappedType(type) { - return getObjectFlags(type) & 32 && - maybeTypeOfKind(getConstraintTypeFromMappedType(type), 540672 | 262144); + return getObjectFlags(type) & 32 && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -24119,6 +24301,10 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + var transformed = getTransformedIndexedAccessType(type); + if (transformed) { + return transformed; + } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; @@ -24181,11 +24367,18 @@ var ts; return stringType; } if (t.flags & 524288) { + var transformed = getTransformedIndexedAccessType(t); + if (transformed) { + return getBaseConstraint(transformed); + } var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; } + if (isGenericMappedType(t)) { + return emptyObjectType; + } return t; } } @@ -24665,6 +24858,9 @@ var ts; } return signature.resolvedReturnType; } + function isResolvingReturnTypeOfSignature(signature) { + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3) >= 0; + } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); @@ -24733,7 +24929,7 @@ var ts; function getIndexInfoOfSymbol(symbol, kind) { var declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64), declaration); } return undefined; } @@ -25001,8 +25197,8 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; switch (declaration.kind) { case 229: case 230: @@ -25459,17 +25655,16 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { + if (!(indexType.flags & 6144) && isTypeAssignableToKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAssignableToKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); - return unknownType; } return indexInfo.type; } @@ -25501,25 +25696,68 @@ var ts; return anyType; } function getIndexedAccessForMappedType(type, indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - return unknownType; + if (accessNode) { + if (!isTypeAssignableTo(indexType, getIndexType(type))) { + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(type)); + return unknownType; + } + if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && type.declaration.readonlyToken) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + } } var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); } + function isGenericObjectType(type) { + return type.flags & 540672 ? true : + getObjectFlags(type) & 32 ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : + type.flags & 196608 ? ts.forEach(type.types, isGenericObjectType) : + false; + } + function isGenericIndexType(type) { + return type.flags & (540672 | 262144) ? true : + type.flags & 196608 ? ts.forEach(type.types, isGenericIndexType) : + false; + } + function isStringIndexOnlyType(type) { + if (type.flags & 32768 && !isGenericMappedType(type)) { + var t = resolveStructuredTypeMembers(type); + return t.properties.length === 0 && + t.callSignatures.length === 0 && t.constructSignatures.length === 0 && + t.stringIndexInfo && !t.numberIndexInfo; + } + return false; + } + function getTransformedIndexedAccessType(type) { + var objectType = type.objectType; + if (objectType.flags & 131072 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0)); + } + else { + regularTypes.push(t); + } + } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + return undefined; + } function getIndexedAccessType(objectType, indexType, accessNode) { - if (maybeTypeOfKind(indexType, 540672 | 262144) || - maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 180) || - isGenericMappedType(objectType)) { + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { return objectType; } - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } var id = objectType.id + "," + indexType.id; var type = indexedAccessTypes.get(id); if (!type) { @@ -25718,7 +25956,7 @@ var ts; var container = ts.getThisContainer(node, false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { - if (!(ts.getModifierFlags(container) & 32) && + if (!ts.hasModifier(container, 32) && (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } @@ -25865,7 +26103,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.signature, mapper.flags | 2, mapper.inferences) : + createInferenceContext(mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : mapper; } function identityMapper(type) { @@ -26129,11 +26367,13 @@ var ts; if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind === 187) { - return false; + if (node.kind !== 187) { + var parameter = ts.firstOrUndefined(node.parameters); + if (!(parameter && ts.parameterIsThisKeyword(parameter))) { + return true; + } } - var parameter = ts.firstOrUndefined(node.parameters); - return !(parameter && ts.parameterIsThisKeyword(parameter)); + return node.body.kind === 207 ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); @@ -26196,7 +26436,7 @@ var ts; return 0; } if (source.typeParameters) { - source = instantiateSignatureInContextOf(source, target); + source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var result = -1; var sourceThisType = getThisTypeOfSignature(source); @@ -26245,7 +26485,7 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(source); if (target.typePredicate) { if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(target.typePredicate)) { if (reportErrors) { @@ -26261,7 +26501,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -26270,11 +26510,13 @@ var ts; return 0; } if (source.kind === 1) { - var sourceIdentifierPredicate = source; - var targetIdentifierPredicate = target; - if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + var sourcePredicate = source; + var targetPredicate = target; + var sourceIndex = sourcePredicate.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); + var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); + if (sourceIndex !== targetIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourcePredicate.parameterName, targetPredicate.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0; @@ -26419,8 +26661,7 @@ var ts; return true; } if (source.flags & 32768 && target.flags & 32768) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); + var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1; } @@ -26533,11 +26774,21 @@ var ts; !(target.flags & 65536) && !isIntersectionConstituent && source !== globalObjectType && - getPropertiesOfType(source).length > 0 && + (getPropertiesOfType(source).length > 0 || + getSignaturesOfType(source, 0).length > 0 || + getSignaturesOfType(source, 1).length > 0) && isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { - reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + var calls = getSignaturesOfType(source, 0); + var constructs = getSignaturesOfType(source, 1); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } } return 0; } @@ -26738,7 +26989,7 @@ var ts; if (overflow) { return 0; } - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var id = getRelationKey(source, target, relation); var related = relation.get(id); if (related !== undefined) { if (reportErrors && related === 2) { @@ -27158,6 +27409,9 @@ var ts; if (sourceInfo) { return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); } + if (isGenericMappedType(source)) { + return kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + } if (isObjectLiteralType(source)) { var related = -1; if (kind === 0) { @@ -27191,8 +27445,8 @@ var ts; if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; - var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24); if (targetAccessibility === 8) { return true; } @@ -27208,6 +27462,42 @@ var ts; return false; } } + function isUnconstrainedTypeParameter(type) { + return type.flags & 16384 && !getConstraintFromTypeParameter(type); + } + function isTypeReferenceWithGenericArguments(type) { + return getObjectFlags(type) & 4 && ts.some(type.typeArguments, isUnconstrainedTypeParameter); + } + function getTypeReferenceId(type, typeParameters) { + var result = "" + type.target.id; + for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { + var t = _a[_i]; + if (isUnconstrainedTypeParameter(t)) { + var index = ts.indexOf(typeParameters, t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + } + else { + result += "-" + t.id; + } + } + return result; + } + function getRelationKey(source, target, relation) { + if (relation === identityRelation && source.id > target.id) { + var temp = source; + source = target; + target = temp; + } + if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { + var typeParameters = []; + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + } + return source.id + "," + target.id; + } function forEachProperty(prop, callback) { if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { @@ -27244,7 +27534,7 @@ var ts; var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.getModifierFlags(declaration) & 128) { + if (declaration && ts.hasModifier(declaration, 128)) { return true; } } @@ -27630,13 +27920,14 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(signature, flags, baseInferences) { + function createInferenceContext(signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); var context = mapper; context.mappedTypes = signature.typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; + context.compareTypes = compareTypes || compareTypesAssignable; return context; function mapper(t) { for (var i = 0; i < inferences.length; i++) { @@ -27724,6 +28015,19 @@ var ts; return inference.candidates && getUnionType(inference.candidates, true); } } + function isPossiblyAssignableTo(source, target) { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + if (!(targetProp.flags & (16777216 | 4194304))) { + var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (!sourceProp) { + return false; + } + } + } + return true; + } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; @@ -27884,15 +28188,17 @@ var ts; return; } } - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target); + if (isPossiblyAssignableTo(source, target) || isPossiblyAssignableTo(target, source)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target); + } } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { - var targetProp = properties_5[_i]; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -27991,7 +28297,7 @@ var ts; var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { inference.inferredType = inferredType = instantiatedConstraint; } } @@ -28039,16 +28345,6 @@ var ts; } return undefined; } - function getLeftmostIdentifierOrThis(node) { - switch (node.kind) { - case 71: - case 99: - return node; - case 179: - return getLeftmostIdentifierOrThis(node.expression); - } - return undefined; - } function getBindingElementNameText(element) { if (element.parent.kind === 174) { var name = element.propertyName || element.name; @@ -28540,7 +28836,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 84); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -28686,7 +28982,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { + if (isTypeAssignableToKind(indexType, 84)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -29372,7 +29668,7 @@ var ts; break; case 149: case 148: - if (ts.getModifierFlags(container) & 32) { + if (ts.hasModifier(container, 32)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -29463,14 +29759,14 @@ var ts; if (!isCallExpression && container.kind === 152) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } - if ((ts.getModifierFlags(container) & 32) || isCallExpression) { + if (ts.hasModifier(container, 32) || isCallExpression) { nodeCheckFlag = 512; } else { nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 151 && ts.getModifierFlags(container) & 256) { + if (container.kind === 151 && ts.hasModifier(container, 256)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } @@ -29515,7 +29811,7 @@ var ts; } else { if (ts.isClassLike(container.parent) || container.parent.kind === 178) { - if (ts.getModifierFlags(container) & 32) { + if (ts.hasModifier(container, 32)) { return container.kind === 151 || container.kind === 150 || container.kind === 153 || @@ -29705,7 +30001,7 @@ var ts; return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); - if (signature) { + if (signature && !isResolvingReturnTypeOfSignature(signature)) { return getReturnTypeOfSignature(signature); } return undefined; @@ -29809,11 +30105,11 @@ var ts; return undefined; } if (ts.isJsxAttribute(node.parent)) { - return getTypeOfPropertyOfType(attributesType, node.parent.name.escapedText); + return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); } else if (node.parent.kind === 249) { var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; + return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; } else { return attributesType; @@ -29825,7 +30121,7 @@ var ts; if (!attributesType || isTypeAny(attributesType)) { return undefined; } - return getTypeOfPropertyOfType(attributesType, attribute.name.escapedText); + return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { return attributesType; @@ -30041,10 +30337,7 @@ var ts; } } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); - } - function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || isTypeOfKind(type, kind); + return isTypeAssignableToKind(checkComputedPropertyName(name), 84); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -30056,7 +30349,9 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { + if (links.resolvedType.flags & 6144 || + !isTypeAssignableToKind(links.resolvedType, 262178 | 84 | 512) && + !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -30541,9 +30836,7 @@ var ts; return undefined; } function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (!elementType) { - elementType = checkExpression(openingLikeElement.tagName); - } + if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } if (elementType.flags & 65536) { var types = elementType.types; return getUnionType(types.map(function (type) { @@ -30638,11 +30931,12 @@ var ts; } function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { + var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; + if (!links[linkLocation]) { var elemClassType = getJsxGlobalElementClassType(); - return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); } - return links.resolvedJsxElementAttributesType; + return links[linkLocation]; } function getAllAttributesTypeFromJsxOpeningLikeElement(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -30869,9 +31163,12 @@ var ts; } var prop = getPropertyOfType(apparentType, right.escapedText); if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0); - if (stringIndexType) { - return stringIndexType; + var indexInfo = getIndexInfoOfType(apparentType, 0); + if (indexInfo && indexInfo.type) { + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + return indexInfo.type; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); @@ -30998,7 +31295,7 @@ var ts; if (prop && noUnusedIdentifiers && (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8)) { if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } @@ -31269,8 +31566,8 @@ var ts; } return undefined; } - function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature, 1); + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + var context = createInferenceContext(signature, 1, compareTypes); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); @@ -31500,7 +31797,7 @@ var ts; return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512)) { + if (isTypeAssignableToKind(nameType, 512)) { return nameType; } else { @@ -31593,9 +31890,10 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); + var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; var excludeArgument; var excludeCount = 0; - if (!isDecorator) { + if (!isDecorator && !isSingleNonGenericCandidate) { for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { if (isContextSensitive(args[i])) { if (!excludeArgument) { @@ -31687,6 +31985,17 @@ var ts; if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; candidateForTypeArgumentError = undefined; + if (isSingleNonGenericCandidate) { + var candidate = candidates[0]; + if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + return undefined; + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + candidateForArgumentError = candidate; + return undefined; + } + return candidate; + } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { @@ -31817,7 +32126,7 @@ var ts; return resolveErrorCall(node); } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { + if (valueDecl && ts.hasModifier(valueDecl, 128)) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } @@ -31853,8 +32162,8 @@ var ts; return true; } var declaration = signature.declaration; - var modifiers = ts.getModifierFlags(declaration); - if (!(modifiers & 24)) { + var modifiers = ts.getSelectedModifierFlags(declaration, 24); + if (!modifiers) { return true; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -32008,7 +32317,7 @@ var ts; && getSymbolLinks(type.symbol).inferredClassType === type; } function checkCallExpression(node) { - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); + checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 97) { return voidType; @@ -32041,7 +32350,7 @@ var ts; return getReturnTypeOfSignature(signature); } function checkImportCallExpression(node) { - checkGrammarArguments(node, node.arguments) || checkGrammarImportCallExpression(node); + checkGrammarArguments(node.arguments) || checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } @@ -32057,11 +32366,33 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeOfSymbol(esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); } } return createPromiseReturnType(node, anyType); } + function getTypeWithSyntheticDefaultImportType(type, symbol) { + if (allowSyntheticDefaultImports && type && type !== unknownType) { + var synthType = type; + if (!synthType.syntheticType) { + if (!getPropertyOfType(type, "default")) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152, "default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default", newSymbol); + var anonymousSymbol = createSymbol(2048, "__type"); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined); + anonymousSymbol.type = defaultContainingObject; + synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + } + else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } function isCommonJsRequire(node) { if (!ts.isRequireCall(node, true)) { return false; @@ -32180,15 +32511,15 @@ var ts; } } } - function assignBindingElementTypes(node) { - if (ts.isBindingPattern(node.name)) { - for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); - } - assignBindingElementTypes(element); + function assignBindingElementTypes(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 71) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + else { + assignBindingElementTypes(element.name); } } } @@ -32197,12 +32528,13 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = contextualType; - var name = ts.getNameOfDeclaration(parameter.valueDeclaration); - if (links.type === emptyObjectType && - (name.kind === 174 || name.kind === 175)) { - links.type = getTypeFromBindingPattern(name); + var decl = parameter.valueDeclaration; + if (decl.name.kind !== 71) { + if (links.type === emptyObjectType) { + links.type = getTypeFromBindingPattern(decl.name); + } + assignBindingElementTypes(decl.name); } - assignBindingElementTypes(parameter.valueDeclaration); } } function createPromiseType(promisedType) { @@ -32403,14 +32735,14 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186) { - checkGrammarForGenerator(node); - } if (checkMode === 1 && isContextSensitive(node)) { checkNodeDeferred(node); return anyFunctionType; } + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 186) { + checkGrammarForGenerator(node); + } var links = getNodeLinks(node); var type = getTypeOfSymbol(node.symbol); if (!(links.flags & 1024)) { @@ -32480,7 +32812,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { + if (!isTypeAssignableToKind(type, 84)) { error(operand, diagnostic); return false; } @@ -32568,8 +32900,13 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + if (node.operand.kind === 8) { + if (node.operator === 38) { + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + } + else if (node.operator === 37) { + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } } switch (node.operator) { case 37: @@ -32621,30 +32958,22 @@ var ts; } return false; } - function isTypeOfKind(type, kind) { - if (type.flags & kind) { + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { return true; } - if (type.flags & 65536) { - var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; - if (!isTypeOfKind(t, kind)) { - return false; - } - } - return true; + if (strict && source.flags & (1 | 1024 | 2048 | 4096)) { + return false; } - if (type.flags & 131072) { - var types = type.types; - for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { - var t = types_19[_a]; - if (isTypeOfKind(t, kind)) { - return true; - } - } - } - return false; + return (kind & 84 && isTypeAssignableTo(source, numberType)) || + (kind & 262178 && isTypeAssignableTo(source, stringType)) || + (kind & 136 && isTypeAssignableTo(source, booleanType)) || + (kind & 1024 && isTypeAssignableTo(source, voidType)) || + (kind & 8192 && isTypeAssignableTo(source, neverType)) || + (kind & 4096 && isTypeAssignableTo(source, nullType)) || + (kind & 2048 && isTypeAssignableTo(source, undefinedType)) || + (kind & 512 && isTypeAssignableTo(source, esSymbolType)) || + (kind & 16777216 && isTypeAssignableTo(source, nonPrimitiveType)); } function isConstEnumObjectType(type) { return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); @@ -32656,7 +32985,7 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (isTypeOfKind(leftType, 8190)) { + if (!isTypeAny(leftType) && isTypeAssignableToKind(leftType, 8190)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(isTypeAny(rightType) || @@ -32673,18 +33002,18 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(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)) { + if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var p = properties_6[_i]; + for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { + var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); } return sourceType; @@ -32940,24 +33269,22 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeOfKind(leftType, 1 | 262178) && !isTypeOfKind(rightType, 1 | 262178)) { + if (!isTypeAssignableToKind(leftType, 262178) && !isTypeAssignableToKind(rightType, 262178)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { + if (isTypeAssignableToKind(leftType, 84, true) && isTypeAssignableToKind(rightType, 84, true)) { resultType = numberType; } - else { - if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { - resultType = stringType; - } - else if (isTypeAny(leftType) || isTypeAny(rightType)) { - resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; - } - if (resultType && !checkForDisallowedESSymbolOperand(operator)) { - return resultType; - } + else if (isTypeAssignableToKind(leftType, 262178, true) || isTypeAssignableToKind(rightType, 262178, true)) { + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; + } + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; } if (!resultType) { reportOperatorError(); @@ -33122,13 +33449,12 @@ var ts; return getBestChoiceType(type1, type2); } function checkLiteralExpression(node) { - if (node.kind === 8) { - checkGrammarNumericLiteral(node); - } switch (node.kind) { + case 13: case 9: return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: + checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; @@ -33276,6 +33602,7 @@ var ts; return checkSuperExpression(node); case 95: return nullWideningType; + case 13: case 9: case 8: case 101: @@ -33283,8 +33610,6 @@ var ts; return checkLiteralExpression(node); case 196: return checkTemplateExpression(node); - case 13: - return stringType; case 12: return globalRegExpType; case 177: @@ -33375,7 +33700,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.getModifierFlags(node) & 92) { + if (ts.hasModifier(node, 92)) { func = ts.getContainingFunction(node); if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -33565,7 +33890,7 @@ var ts; } } else { - var isStatic = ts.getModifierFlags(member) & 32; + var isStatic = ts.hasModifier(member, 32); var names = isStatic ? staticNames : instanceNames; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { @@ -33610,7 +33935,7 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; var memberNameNode = member.name; - var isStatic = ts.getModifierFlags(member) & 32; + var isStatic = ts.hasModifier(member, 32); if (isStatic && memberNameNode) { var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); switch (memberName) { @@ -33698,7 +34023,7 @@ var ts; function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); checkFunctionOrMethodDeclaration(node); - if (ts.getModifierFlags(node) & 128 && node.body) { + if (ts.hasModifier(node, 128) && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -33734,17 +34059,9 @@ var ts; } return ts.forEachChild(n, containsSuperCall); } - function markThisReferencesAsErrors(n) { - if (n.kind === 99) { - error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - } - else if (n.kind !== 186 && n.kind !== 228) { - ts.forEachChild(n, markThisReferencesAsErrors); - } - } function isInstancePropertyWithInitializer(n) { return n.kind === 149 && - !(ts.getModifierFlags(n) & 32) && + !ts.hasModifier(n, 32) && !!n.initializer; } var containingClassDecl = node.parent; @@ -33756,8 +34073,8 @@ var ts; if (classExtendsNull) { error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); + var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92); }); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; @@ -33800,10 +34117,12 @@ var ts; var otherKind = node.kind === 153 ? 154 : 153; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { + var nodeFlags = ts.getModifierFlags(node); + var otherFlags = ts.getModifierFlags(otherAccessor); + if ((nodeFlags & 28) !== (otherFlags & 28)) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { + if ((nodeFlags & 128) !== (otherFlags & 128)) { error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); @@ -33849,7 +34168,7 @@ var ts; function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); if (node.kind === 159 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { - grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); if (type !== unknownType) { @@ -33857,7 +34176,14 @@ var ts; ts.forEach(node.typeArguments, checkSourceElement); if (produceDiagnostics) { var symbol = getNodeLinks(node).resolvedSymbol; - var typeParameters = symbol.flags & 524288 ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; + if (!symbol) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return; + } + var typeParameters = symbol.flags & 524288 && getSymbolLinks(symbol).typeParameters; + if (!typeParameters && getObjectFlags(type) & 4) { + typeParameters = type.target.localTypeParameters; + } checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } @@ -33900,16 +34226,15 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { - var constraint = getBaseConstraintOfType(objectType); - if (constraint && getIndexInfoOfType(constraint, 1)) { - return type; - } + if (getIndexInfoOfType(getApparentType(objectType), 1) && isTypeAssignableToKind(indexType, 84)) { + return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); return type; } function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } function checkMappedType(node) { @@ -33920,7 +34245,7 @@ var ts; checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); } function isPrivateWithinAmbient(node) { - return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); + return ts.hasModifier(node, 8) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); @@ -34007,9 +34332,9 @@ var ts; (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { var reportError = (node.kind === 151 || node.kind === 150) && - (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); + ts.hasModifier(node, 32) !== ts.hasModifier(subsequentNode, 32); if (reportError) { - var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + var diagnostic = ts.hasModifier(node, 32) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -34025,7 +34350,7 @@ var ts; error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); } else { - if (ts.getModifierFlags(node) & 128) { + if (ts.hasModifier(node, 128)) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -34035,8 +34360,8 @@ var ts; } var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var current = declarations_5[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; @@ -34085,7 +34410,7 @@ var ts; }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -34494,7 +34819,7 @@ var ts; if (!ts.hasDynamicName(node)) { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)); }); + var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536); }); if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); } @@ -34629,14 +34954,14 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 151 || member.kind === 149) { - if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { + if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); } } else if (member.kind === 152) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); } } @@ -34976,7 +35301,7 @@ var ts; 128 | 64 | 32; - return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); + return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); @@ -35106,7 +35431,7 @@ var ts; checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { + if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -35478,7 +35803,7 @@ var ts; var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { + if (!ts.hasModifier(member, 32) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); @@ -35575,8 +35900,8 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { var name = symbolToString(symbol); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } @@ -35585,8 +35910,8 @@ var ts; function areTypeParametersIdentical(declarations, typeParameters) { var maxTypeArgumentCount = ts.length(typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; var numTypeParameters = ts.length(declaration.typeParameters); if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { return false; @@ -35622,7 +35947,7 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (!node.name && !(ts.getModifierFlags(node) & 512)) { + if (!node.name && !ts.hasModifier(node, 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -35715,7 +36040,7 @@ var ts; var signatures = getSignaturesOfType(type, 1); if (signatures.length) { var declaration = signatures[0].declaration; - if (declaration && ts.getModifierFlags(declaration) & 8) { + if (declaration && ts.hasModifier(declaration, 8)) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); @@ -35748,7 +36073,7 @@ var ts; if (derived) { if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128))) { if (derivedClassDecl.kind === 199) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -35796,8 +36121,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { - var prop = properties_7[_a]; + for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { + var prop = properties_8[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -36051,8 +36376,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; if ((declaration.kind === 229 || (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { @@ -36267,7 +36592,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -36294,7 +36619,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (ts.getModifierFlags(node) & 1) { + if (ts.hasModifier(node, 1)) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -36322,7 +36647,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -36380,7 +36705,7 @@ var ts; } return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 71) { @@ -36427,8 +36752,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -36706,7 +37031,7 @@ var ts; return []; } var symbols = ts.createSymbolTable(); - var memberFlags = 0; + var isStatic = false; populateSymbols(); return symbolsToArray(symbols); function populateSymbols() { @@ -36728,7 +37053,7 @@ var ts; } case 229: case 230: - if (!(memberFlags & 32)) { + if (!isStatic) { copySymbols(getSymbolOfNode(location).members, meaning & 793064); } break; @@ -36742,7 +37067,7 @@ var ts; if (ts.introducesArgumentsExoticObject(location)) { copySymbol(argumentsSymbol, meaning); } - memberFlags = ts.getModifierFlags(location); + isStatic = ts.hasModifier(location, 32); location = location.parent; } copySymbols(globals, meaning); @@ -36977,12 +37302,7 @@ var ts; case 8: if (node.parent.kind === 180 && node.parent.argumentExpression === node) { var objectType = getTypeOfExpression(node.parent.expression); - if (objectType === unknownType) - return undefined; - var apparentType = getApparentType(objectType); - if (apparentType === unknownType) - return undefined; - return getPropertyOfType(apparentType, node.text); + return getPropertyOfType(objectType, node.text); } break; } @@ -37078,7 +37398,7 @@ var ts; } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return ts.getModifierFlags(node) & 32 + return ts.hasModifier(node, 32) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -37303,13 +37623,13 @@ var ts; return strictNullChecks && !isOptionalParameter(parameter) && parameter.initializer && - !(ts.getModifierFlags(parameter) & 92); + !ts.hasModifier(parameter, 92); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - !!(ts.getModifierFlags(parameter) & 92); + ts.hasModifier(parameter, 92); } function getNodeCheckFlags(node) { return getNodeLinks(node).flags; @@ -37365,22 +37685,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { + else if (isTypeAssignableToKind(type, 1024 | 6144 | 8192)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeOfKind(type, 136)) { + else if (isTypeAssignableToKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 84)) { + else if (isTypeAssignableToKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 262178)) { + else if (isTypeAssignableToKind(type, 262178)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 512)) { + else if (isTypeAssignableToKind(type, 512)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -37845,7 +38165,7 @@ var ts; node.kind !== 154) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 229 && ts.getModifierFlags(node.parent) & 128)) { + if (!(node.parent.kind === 229 && ts.hasModifier(node.parent, 128))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -37964,8 +38284,7 @@ var ts; if (list && list.hasTrailingComma) { var start = list.end - ",".length; var end = list.end; - var sourceFile = ts.getSourceFileOfNode(list[0]); - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + return grammarErrorAtPos(list[0], start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); } } function checkGrammarTypeParameterList(typeParameters, file) { @@ -38041,7 +38360,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (ts.getModifierFlags(parameter) !== 0) { + if (ts.hasModifiers(parameter)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -38075,19 +38394,18 @@ var ts; return checkGrammarForDisallowedTrailingComma(typeArguments) || checkGrammarForAtLeastOneTypeArgument(node, typeArguments); } - function checkGrammarForOmittedArgument(node, args) { + function checkGrammarForOmittedArgument(args) { if (args) { - var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; if (arg.kind === 200) { - return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } } } - function checkGrammarArguments(node, args) { - return checkGrammarForOmittedArgument(node, args); + function checkGrammarArguments(args) { + return checkGrammarForOmittedArgument(args); } function checkGrammarHeritageClause(node) { var types = node.types; @@ -38096,8 +38414,7 @@ var ts; } if (types && types.length === 0) { var listType = ts.tokenToString(node.token); - var sourceFile = ts.getSourceFileOfNode(node); - return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } return ts.forEach(types, checkGrammarExpressionWithTypeArguments); } @@ -38320,10 +38637,10 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { - return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } - else if (accessor.body && ts.getModifierFlags(accessor) & 128) { + else if (accessor.body && ts.hasModifier(accessor, 128)) { return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); } else if (accessor.typeParameters) { @@ -38376,7 +38693,7 @@ var ts; return true; } else if (node.body === undefined) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } if (ts.isClassLike(node.parent)) { @@ -38447,7 +38764,7 @@ var ts; return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } } } @@ -38467,12 +38784,12 @@ var ts; } else { var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } else if (!node.initializer) { @@ -38529,7 +38846,7 @@ var ts; return true; } if (!declarationList.declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } } function allowLetAndConstDeclarations(parent) { @@ -38575,7 +38892,8 @@ var ts; return true; } } - function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { + function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); if (!hasParseDiagnostics(sourceFile)) { diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; @@ -38590,7 +38908,7 @@ var ts; } function checkGrammarConstructorTypeParameters(node) { if (node.typeParameters) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + return grammarErrorAtPos(node, node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -38632,7 +38950,7 @@ var ts; node.kind === 244 || node.kind === 243 || node.kind === 236 || - ts.getModifierFlags(node) & (2 | 1 | 512)) { + ts.hasModifier(node, 2 | 1 | 512)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -41401,27 +41719,27 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_8 = []; + var properties_9 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_8.push(getter); + properties_9.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_8.push(setter); + properties_9.push(setter); } - properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_8, multiLine) + ts.createObjectLiteral(properties_9, multiLine) ]), firstAccessor); return ts.aggregateTransformFlags(expression); } @@ -43361,7 +43679,8 @@ var ts; ? undefined : numElements, location), false, location); } - else if (numElements !== 1 && (flattenContext.level < 1 || numElements === 0)) { + else if (numElements !== 1 && (flattenContext.level < 1 || numElements === 0) + || ts.every(elements, ts.isOmittedExpression)) { var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); } @@ -43568,7 +43887,12 @@ var ts; if (ts.hasModifier(node, 2)) { break; } - recordEmittedDeclarationInScope(node); + if (node.name) { + recordEmittedDeclarationInScope(node); + } + else { + ts.Debug.assert(node.kind === 229 || ts.hasModifier(node, 512)); + } break; } } @@ -43982,8 +44306,8 @@ var ts; && member.initializer !== undefined; } function addInitializedPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { - var property = properties_9[_i]; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; var statement = ts.createStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); @@ -43992,8 +44316,8 @@ var ts; } function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { - var property = properties_10[_i]; + for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { + var property = properties_11[_i]; var expression = transformInitializedProperty(property, receiver); expression.startsOnNewLine = true; ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); @@ -44688,24 +45012,24 @@ var ts; && moduleKind !== ts.ModuleKind.System); } function recordEmittedDeclarationInScope(node) { - var name = node.symbol && node.symbol.escapedName; - if (name) { - if (!currentScopeFirstDeclarationsOfName) { - currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); - } - if (!currentScopeFirstDeclarationsOfName.has(name)) { - currentScopeFirstDeclarationsOfName.set(name, node); - } + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); + } + var name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); } } function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name = node.symbol && node.symbol.escapedName; - if (name) { - return currentScopeFirstDeclarationsOfName.get(name) === node; - } + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; } - return false; + return true; + } + function declaredNameInScope(node) { + ts.Debug.assertNode(node.name, ts.isIdentifier); + return node.name.escapedText; } function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ @@ -44736,7 +45060,7 @@ var ts; if (!shouldEmitModuleDeclaration(node)) { return ts.createNotEmittedStatement(node); } - ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); + ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); enableSubstitutionForNamespaceExports(); var statements = []; var emitFlags = 2; @@ -45460,6 +45784,8 @@ var ts; return visitExpressionStatement(node); case 185: return visitParenthesizedExpression(node, noDestructuringValue); + case 260: + return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); } @@ -45534,6 +45860,12 @@ var ts; function visitParenthesizedExpression(node, noDestructuringValue) { return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } function visitBinaryExpression(node, noDestructuringValue) { if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576) { return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); @@ -45980,7 +46312,7 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -46567,7 +46899,7 @@ var ts; function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 && ts.isStatement(node)) + || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 207))) || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) || isTypeScriptClassWrapper(node); } @@ -46847,9 +47179,11 @@ var ts; var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); ts.setEmitFlags(outer, 1536); - return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement + var result = ts.createParen(ts.createCall(outer, undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); + ts.addSyntheticLeadingComment(result, 3, "* @class "); + return result; } function transformClassBody(node, extendsClauseElement) { var statements = []; @@ -47434,11 +47768,12 @@ var ts; ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); if (node.transformFlags & 8388608 - && (ts.isBindingPattern(node.declarations[0].name) - || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + if (firstDeclaration) { + var lastDeclaration = ts.lastOrUndefined(declarations); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } } return declarationList; } @@ -47977,6 +48312,7 @@ var ts; function visitCatchClause(node) { var ancestorFacts = enterSubtree(4032, 0); var updated; + ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); if (ts.isBindingPattern(node.variableDeclaration.name)) { var temp = ts.createTempVariable(undefined); var newVariableDeclaration = ts.createVariableDeclaration(temp); @@ -49224,8 +49560,12 @@ var ts; } function transformAndEmitContinueStatement(node) { var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); - ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); - emitBreak(label, node); + if (label > 0) { + emitBreak(label, node); + } + else { + emitStatement(node); + } } function visitContinueStatement(node) { if (inStatementContainingYield) { @@ -49238,8 +49578,12 @@ var ts; } function transformAndEmitBreakStatement(node) { var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); - ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); - emitBreak(label, node); + if (label > 0) { + emitBreak(label, node); + } + else { + emitStatement(node); + } } function visitBreakStatement(node) { if (inStatementContainingYield) { @@ -49496,9 +49840,6 @@ var ts; var block = endBlock(); markLabel(block.endLabel); } - function isWithBlock(block) { - return block.kind === 1; - } function beginExceptionBlock() { var startLabel = defineLabel(); var endLabel = defineLabel(); @@ -49567,9 +49908,6 @@ var ts; emitNop(); exception.state = 3; } - function isExceptionBlock(block) { - return block.kind === 0; - } function beginScriptLoopBlock() { beginBlock({ kind: 3, @@ -49669,43 +50007,45 @@ var ts; return false; } function findBreakTarget(labelText) { - ts.Debug.assert(blocks !== undefined); - if (labelText) { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { - return block.breakLabel; - } - else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { - return block.breakLabel; + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } } } - } - else { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledBreak(block)) { - return block.breakLabel; + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } } } } return 0; } function findContinueTarget(labelText) { - ts.Debug.assert(blocks !== undefined); - if (labelText) { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { - return block.continueLabel; + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } } } - } - else { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledContinue(block)) { - return block.continueLabel; + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } } } } @@ -49733,7 +50073,7 @@ var ts; return literal; } function createInlineBreak(label, location) { - ts.Debug.assert(label > 0, "Invalid label: " + label); + ts.Debug.assertLessThan(0, label, "Invalid label"); return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ createInstruction(3), createLabel(label) @@ -49941,31 +50281,33 @@ var ts; for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { var block = blocks[blockIndex]; var blockAction = blockActions[blockIndex]; - if (isExceptionBlock(block)) { - if (blockAction === 0) { - if (!exceptionBlockStack) { - exceptionBlockStack = []; + switch (block.kind) { + case 0: + if (blockAction === 0) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; } - if (!statements) { - statements = []; + else if (blockAction === 1) { + currentExceptionBlock = exceptionBlockStack.pop(); } - exceptionBlockStack.push(currentExceptionBlock); - currentExceptionBlock = block; - } - else if (blockAction === 1) { - currentExceptionBlock = exceptionBlockStack.pop(); - } - } - else if (isWithBlock(block)) { - if (blockAction === 0) { - if (!withBlockStack) { - withBlockStack = []; + break; + case 1: + if (blockAction === 0) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); } - withBlockStack.push(block); - } - else if (blockAction === 1) { - withBlockStack.pop(); - } + else if (blockAction === 1) { + withBlockStack.pop(); + } + break; } } } @@ -52275,7 +52617,6 @@ var ts; errorNameNode = declaration.name; var format = 4 | 16384 | - 2048 | (shouldUseResolverType ? 8192 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; @@ -52289,7 +52630,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 2048 | 16384, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 16384, writer); errorNameNode = undefined; } } @@ -52519,7 +52860,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 2048 | 16384, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 16384, writer); write(";"); writeLine(); return tempVarName; @@ -53156,6 +53497,9 @@ var ts; return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); } function writeVariableStatement(node) { + if (ts.every(node.declarationList && node.declarationList.declarations, function (decl) { return decl.name && ts.isEmptyBindingPattern(decl.name); })) { + return; + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.isLet(node.declarationList)) { @@ -54121,14 +54465,14 @@ var ts; writer.writeLine(); } } - function emitTrailingCommentsOfPosition(pos) { + function emitTrailingCommentsOfPosition(pos, prefixSpace) { if (disabled) { return; } if (extendedDiagnostics) { ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); } - forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); if (extendedDiagnostics) { ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); } @@ -54208,15 +54552,7 @@ var ts; emitPos(commentEnd); } function isTripleSlashComment(commentPos, commentEnd) { - if (currentText.charCodeAt(commentPos + 1) === 47 && - commentPos + 2 < commentEnd && - currentText.charCodeAt(commentPos + 2) === 47) { - var textSubStr = currentText.substring(commentPos, commentEnd); - return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || - textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? - true : false; - } - return false; + return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); } } ts.createCommentWriter = createCommentWriter; @@ -55155,7 +55491,9 @@ var ts; if (!(ts.getEmitFlags(node) & 131072)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = { kind: 23, pos: dotRangeStart, end: dotRangeEnd }; + var dotToken = ts.createToken(23); + dotToken.pos = dotRangeStart; + dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } @@ -55267,7 +55605,9 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + emitLeadingCommentsOfPosition(node.operatorToken.pos); writeTokenNode(node.operatorToken); + emitTrailingCommentsOfPosition(node.operatorToken.end, true); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -55454,8 +55794,19 @@ var ts; emitWithPrefix(" ", node.label); write(";"); } + function emitTokenWithComment(token, pos, contextNode) { + var node = contextNode && ts.getParseTreeNode(contextNode); + if (node && node.kind === contextNode.kind) { + pos = ts.skipTrivia(currentSourceFile.text, pos); + } + pos = writeToken(token, pos, contextNode); + if (node && node.kind === contextNode.kind) { + emitTrailingCommentsOfPosition(pos, true); + } + return pos; + } function emitReturnStatement(node) { - writeToken(96, node.pos, node); + emitTokenWithComment(96, node.pos, node); emitExpressionWithPrefix(" ", node.expression); write(";"); } @@ -55896,10 +56247,12 @@ var ts; function emitCatchClause(node) { var openParenPos = writeToken(74, node.pos); write(" "); - writeToken(19, openParenPos); - emit(node.variableDeclaration); - writeToken(20, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); - write(" "); + if (node.variableDeclaration) { + writeToken(19, openParenPos); + emit(node.variableDeclaration); + writeToken(20, node.variableDeclaration.end); + write(" "); + } emit(node.block); } function emitPropertyAssignment(node) { @@ -57011,6 +57364,9 @@ var ts; var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } + var packageIdToSourceFile = ts.createMap(); + var sourceFileToPackageName = ts.createMap(); + var redirectTargetsSet = ts.createMap(); var filesByName = ts.createMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; var structuralIsReused = tryReuseStructureFromOldProgram(); @@ -57067,6 +57423,8 @@ var ts; isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsSet: redirectTargetsSet, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -57210,17 +57568,51 @@ var ts; var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2; - for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { - var oldSourceFile = _a[_i]; + var oldSourceFiles = oldProgram.getSourceFiles(); + var SeenPackageName; + (function (SeenPackageName) { + SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; + SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; + })(SeenPackageName || (SeenPackageName = {})); + var seenPackageNames = ts.createMap(); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { return oldProgram.structureIsReused = 0; } + ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + var fileChanged = void 0; + if (oldSourceFile.redirectInfo) { + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + return oldProgram.structureIsReused = 0; + } + fileChanged = false; + newSourceFile = oldSourceFile; + } + else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + if (newSourceFile !== oldSourceFile) { + return oldProgram.structureIsReused = 0; + } + fileChanged = false; + } + else { + fileChanged = newSourceFile !== oldSourceFile; + } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); - if (oldSourceFile !== newSourceFile) { + var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== undefined) { + var prevKind = seenPackageNames.get(packageName); + var newKind = fileChanged ? 1 : 0; + if ((prevKind !== undefined && newKind === 1) || prevKind === 1) { + return oldProgram.structureIsReused = 0; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { oldProgram.structureIsReused = 1; } @@ -57248,8 +57640,8 @@ var ts; 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; + for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { + var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); @@ -57283,8 +57675,8 @@ var ts; if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { return oldProgram.structureIsReused = 1; } - for (var _d = 0, _e = oldProgram.getMissingFilePaths(); _d < _e.length; _d++) { - var p = _e[_d]; + for (var _c = 0, _d = oldProgram.getMissingFilePaths(); _c < _d.length; _c++) { + var p = _d[_c]; filesByName.set(p, undefined); } for (var i = 0; i < newSourceFiles.length; i++) { @@ -57292,11 +57684,13 @@ var ts; } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _f = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _f < modifiedSourceFiles_2.length; _f++) { - var modifiedFile = modifiedSourceFiles_2[_f]; + for (var _e = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _e < modifiedSourceFiles_2.length; _e++) { + var modifiedFile = modifiedSourceFiles_2[_e]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsSet = oldProgram.redirectTargetsSet; return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { @@ -57775,7 +58169,7 @@ var ts; } } function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, undefined); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -57792,7 +58186,24 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + var redirect = Object.create(redirectTarget); + redirect.fileName = fileName; + redirect.path = path; + redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + Object.defineProperties(redirect, { + id: { + get: function () { return this.redirectInfo.redirectTarget.id; }, + set: function (value) { this.redirectInfo.redirectTarget.id = value; }, + }, + symbol: { + get: function () { return this.redirectInfo.redirectTarget.symbol; }, + set: function (value) { this.redirectInfo.redirectTarget.symbol = value; }, + }, + }); + return redirect; + } + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) { if (filesByName.has(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { @@ -57823,6 +58234,22 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + if (packageId) { + var packageIdKey = packageId.name + "@" + packageId.version; + var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); + redirectTargetsSet.set(fileFromPackageId.path, true); + filesByName.set(path, dupFile); + sourceFileToPackageName.set(path, packageId.name); + files.push(dupFile); + return dupFile; + } + else if (file) { + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageId.name); + } + } filesByName.set(path, file); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); @@ -57944,7 +58371,7 @@ var ts; else if (shouldAddFile) { var path = toPath(resolvedFileName); var pos = ts.skipTrivia(file.text, file.imports[i].pos); - findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end); + findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end, resolution.packageId); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -58623,6 +59050,12 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, { name: "sourceRoot", type: "string", @@ -59234,7 +59667,7 @@ var ts; var text = valueExpression.text; if (option && typeof option.type !== "string") { var customOption = option; - if (!customOption.type.has(text)) { + if (!customOption.type.has(text.toLowerCase())) { errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); } } @@ -59485,12 +59918,10 @@ var ts; } } else { - var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - specs.push(outDir); + excludeSpecs = [outDir]; } - excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; @@ -59741,7 +60172,7 @@ var ts; return value; } else if (typeof option.type !== "string") { - return option.type.get(value); + return option.type.get(typeof value === "string" ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -59816,23 +60247,13 @@ var ts; }; } function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { - var validSpecs = []; - for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { - var spec = specs_1[_i]; - if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); } - else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); - } - else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); - } - else { - validSpecs.push(spec); - } - } - return validSpecs; + return diag === undefined; + }); function createDiagnostic(message, spec) { if (jsonSourceFile && jsonSourceFile.jsonObject) { for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { @@ -59850,6 +60271,17 @@ var ts; return ts.createCompilerDiagnostic(message, spec); } } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); @@ -60758,7 +61190,9 @@ var ts; } ts.findNextToken = findNextToken; function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { - return find(startNode || sourceFile); + var result = find(startNode || sourceFile); + ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); + return result; function findRightmostToken(n) { if (ts.isToken(n)) { return n; @@ -60774,10 +61208,11 @@ var ts; var children = n.getChildren(); for (var i = 0; i < children.length; i++) { var child = children[i]; - if (position < child.end && (nodeHasTokens(child) || child.kind === 10)) { + if (position < child.end) { var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || - (child.kind === 10 && start === child.end); + !nodeHasTokens(child) || + isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { var candidate = findRightmostChildNodeWithTokens(children, i); return candidate && findRightmostToken(candidate); @@ -60795,7 +61230,11 @@ var ts; } function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { for (var i = exclusiveStartPosition - 1; i >= 0; i--) { - if (nodeHasTokens(children[i])) { + var child = children[i]; + if (isWhiteSpaceOnlyJsxText(child)) { + ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + } + else if (nodeHasTokens(children[i])) { return children[i]; } } @@ -60840,34 +61279,19 @@ var ts; return false; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isWhiteSpaceOnlyJsxText(node) { + return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; + } + ts.isWhiteSpaceOnlyJsxText = isWhiteSpaceOnlyJsxText; function isInTemplateString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position, false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; function isInComment(sourceFile, position, tokenAtPosition, predicate) { - if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, false); } - return position <= tokenAtPosition.getStart(sourceFile) && - (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || - isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); - function isInCommentRange(commentRanges) { - return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); - } + return !!ts.formatting.getRangeOfEnclosingComment(sourceFile, position, false, undefined, tokenAtPosition, predicate); } 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; - } - } function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position, false); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); @@ -61220,6 +61644,7 @@ var ts; } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + flags |= 65536; return mapToDisplayParts(function (writer) { typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); }); @@ -61925,11 +62350,11 @@ var ts; templateStack.pop(); } else { - ts.Debug.assert(token === 15, "Should have been a template middle. Was " + token); + ts.Debug.assertEqual(token, 15, "Should have been a template middle."); } } else { - ts.Debug.assert(lastTemplateStackToken === 17, "Should have been an open brace. Was: " + token); + ts.Debug.assertEqual(lastTemplateStackToken, 17, "Should have been an open brace"); templateStack.pop(); } } @@ -63587,7 +64012,7 @@ var ts; var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); if (!typeForObject) return false; - typeMembers = typeChecker.getPropertiesOfType(typeForObject); + typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24); }); existingMembers = objectLikeContainer.elements; } } @@ -63964,8 +64389,8 @@ var ts; addPropertySymbols(implementingTypeSymbols, 24); return result; function addPropertySymbols(properties, inValidModifierFlags) { - for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { - var property = properties_11[_i]; + for (var _i = 0, properties_12 = properties; _i < properties_12.length; _i++) { + var property = properties_12[_i]; if (isValidProperty(property, inValidModifierFlags)) { result.push(property); } @@ -65655,11 +66080,15 @@ var ts; } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - if (bindingElement) { - var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + if (!bindingElement) + return undefined; + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + if (propSymbol && propSymbol.flags & 98304) { + ts.Debug.assert(!!(propSymbol.flags & 33554432)); + return propSymbol.target; } - return undefined; + return propSymbol; } function getSymbolScope(symbol) { var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; @@ -65679,12 +66108,13 @@ var ts; if (getObjectBindingElementWithoutPropertyName(symbol)) { return undefined; } - if (parent && !((parent.flags & 1536) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + var exposedByParent = parent && !(symbol.flags & 262144); + if (exposedByParent && !((parent.flags & 1536) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { return undefined; @@ -65694,7 +66124,7 @@ var ts; } scope = container; } - return parent ? scope.getSourceFile() : scope; + return exposedByParent ? scope.getSourceFile() : scope; } function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } @@ -66371,8 +66801,8 @@ var ts; var lastIterationMeaning = void 0; do { lastIterationMeaning = meaning; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -66517,6 +66947,16 @@ 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.isPropertyName(node) && ts.isBindingElement(node.parent) && ts.isObjectBindingPattern(node.parent.parent) && + (node === (node.parent.propertyName || node.parent.name))) { + var type = typeChecker.getTypeAtLocation(node.parent.parent); + if (type) { + var propSymbols = ts.getPropertySymbolsFromType(type, node); + if (propSymbols) { + return ts.flatMap(propSymbols, function (propSymbol) { return getDefinitionFromSymbol(typeChecker, propSymbol, node); }); + } + } + } var element = ts.getContainingObjectLiteralElement(node); if (element && typeChecker.getContextualType(element.parent)) { return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { @@ -66933,12 +67373,20 @@ var ts; "crypto", "stream", "util", "assert", "tty", "domain", "constants", "process", "v8", "timers", "console" ]; - var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); + var nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); function loadSafeList(host, safeListPath) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); return ts.createMapFromTemplate(result.config); } JsTyping.loadSafeList = loadSafeList; + function loadTypesMap(host, typesMapPath) { + var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); + if (result.config) { + return ts.createMapFromTemplate(result.config.simpleMap); + } + return undefined; + } + JsTyping.loadTypesMap = loadTypesMap; function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; @@ -67093,8 +67541,8 @@ var ts; if (!matches) { return; } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; if (patternMatcher.patternContainsDots) { var containers = getContainers(declaration); if (!containers) { @@ -67753,13 +68201,17 @@ var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { + var collapseText = "..."; + var maxDepth = 20; function collectElements(sourceFile, cancellationToken) { var elements = []; - var collapseText = "..."; - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { + var depth = 0; + walk(sourceFile); + return elements; + function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { if (hintSpanNode && startElement && endElement) { var span_13 = { - textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), + textSpan: ts.createTextSpanFromBounds(useFullStart ? startElement.getFullStart() : startElement.getStart(), endElement.getEnd()), hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), bannerText: collapseText, autoCollapse: autoCollapse, @@ -67820,8 +68272,6 @@ var ts; function autoCollapse(node) { return ts.isFunctionBlock(node) && node.parent.kind !== 187; } - var depth = 0; - var maxDepth = 20; function walk(n) { cancellationToken.throwIfCancellationRequested(); if (depth > maxDepth) { @@ -67834,8 +68284,8 @@ var ts; case 207: if (!ts.isFunctionBlock(n)) { var parent = n.parent; - var openBrace = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18, sourceFile); + var openBrace_1 = ts.findChildOfKind(n, 17, sourceFile); + var closeBrace_1 = ts.findChildOfKind(n, 18, sourceFile); if (parent.kind === 212 || parent.kind === 215 || parent.kind === 216 || @@ -67844,19 +68294,19 @@ var ts; parent.kind === 213 || parent.kind === 220 || parent.kind === 260) { - addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), true); break; } if (parent.kind === 224) { var tryStatement = parent; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), true); break; } else if (tryStatement.finallyBlock === n) { var finallyKeyword = ts.findChildOfKind(tryStatement, 87, sourceFile); if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(finallyKeyword, openBrace_1, closeBrace_1, autoCollapse(n), true); break; } } @@ -67871,33 +68321,35 @@ var ts; break; } case 234: { - var openBrace = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18, sourceFile); - addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + var openBrace_2 = ts.findChildOfKind(n, 17, sourceFile); + var closeBrace_2 = ts.findChildOfKind(n, 18, sourceFile); + addOutliningSpan(n.parent, openBrace_2, closeBrace_2, autoCollapse(n), true); break; } case 229: case 230: case 232: - case 178: case 235: { - var openBrace = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); + var openBrace_3 = ts.findChildOfKind(n, 17, sourceFile); + var closeBrace_3 = ts.findChildOfKind(n, 18, sourceFile); + addOutliningSpan(n, openBrace_3, closeBrace_3, autoCollapse(n), true); break; } + case 178: + var openBrace = ts.findChildOfKind(n, 17, sourceFile); + var closeBrace = ts.findChildOfKind(n, 18, sourceFile); + addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n), !ts.isArrayLiteralExpression(n.parent)); + break; case 177: var openBracket = ts.findChildOfKind(n, 21, sourceFile); var closeBracket = ts.findChildOfKind(n, 22, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); + addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n), !ts.isArrayLiteralExpression(n.parent)); break; } depth++; ts.forEachChild(n, walk); depth--; } - walk(sourceFile); - return elements; } OutliningElementsCollector.collectElements = collectElements; })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); @@ -68741,8 +69193,8 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - for (var _b = 0, declarations_13 = declarations; _b < declarations_13.length; _b++) { - var declaration = declarations_13[_b]; + for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { + var declaration = declarations_12[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -68775,7 +69227,9 @@ var ts; } var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 : 1; var argumentCount = getArgumentCount(list); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } @@ -68853,7 +69307,9 @@ var ts; var argumentCount = tagExpression.template.kind === 13 ? 1 : tagExpression.template.templateSpans.length + 1; - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } return { kind: 2, invocation: tagExpression, @@ -68950,7 +69406,9 @@ var ts; tags: candidateSignature.getJsDocTags() }; }); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } var selectedItemIndex = candidates.indexOf(resolvedSignature); ts.Debug.assert(selectedItemIndex !== -1); return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; @@ -69091,102 +69549,100 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (type) { - if (location.parent && location.parent.kind === 179) { - var right = location.parent.name; - if (right === location || (right && right.getFullWidth() === 0)) { - location = location.parent; + if (location.parent && location.parent.kind === 179) { + var right = location.parent.name; + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + var callExpressionLike = void 0; + if (ts.isCallOrNewExpression(location)) { + callExpressionLike = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpressionLike = location.parent; + } + else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { + callExpressionLike = location.parent; + } + if (callExpressionLike) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); + if (!signature && candidateSignatures.length) { + signature = candidateSignatures[0]; + } + var useConstructSignatures = callExpressionLike.kind === 182 || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97); + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32)) { + symbolKind = "constructor"; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } - } - var callExpressionLike = void 0; - if (ts.isCallOrNewExpression(location)) { - callExpressionLike = location; - } - else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { - callExpressionLike = location.parent; - } - else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { - callExpressionLike = location.parent; - } - if (callExpressionLike) { - var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); - if (!signature && candidateSignatures.length) { - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpressionLike.kind === 182 || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97); - var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { - signature = allSignatures.length ? allSignatures[0] : undefined; - } - if (signature) { - if (useConstructSignatures && (symbolFlags & 32)) { - symbolKind = "constructor"; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + else if (symbolFlags & 2097152) { + symbolKind = "alias"; + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(94)); + displayParts.push(ts.spacePart()); } - else if (symbolFlags & 2097152) { - symbolKind = "alias"; - pushTypePart(symbolKind); + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case "JSX attribute": + case "property": + case "var": + case "const": + case "let": + case "parameter": + case "local var": + displayParts.push(ts.punctuationPart(56)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { displayParts.push(ts.keywordPart(94)); displayParts.push(ts.spacePart()); } - addFullSymbolName(symbol); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - switch (symbolKind) { - case "JSX attribute": - case "property": - case "var": - case "const": - case "let": - case "parameter": - case "local var": - displayParts.push(ts.punctuationPart(56)); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94)); - displayParts.push(ts.spacePart()); - } - if (!(type.flags & 32768 && type.objectFlags & 16) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); - } - addSignatureDisplayParts(signature, allSignatures, 16); - break; - default: - addSignatureDisplayParts(signature, allSignatures); - } - hasAddedSymbolInfo = true; + if (!(type.flags & 32768 && type.objectFlags & 16) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); + } + addSignatureDisplayParts(signature, allSignatures, 16); + break; + default: + addSignatureDisplayParts(signature, allSignatures); } + hasAddedSymbolInfo = true; } - else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304)) || - (location.kind === 123 && location.parent.kind === 152)) { - 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 = "constructor"; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 && - !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304)) || + (location.kind === 123 && location.parent.kind === 152)) { + var functionDeclaration_1 = location.parent; + var locationIsSymbolDeclaration = ts.find(symbol.declarations, 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 = "constructor"; + 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; } } } @@ -69361,7 +69817,9 @@ var ts; symbolFlags & 98304 || symbolKind === "method") { var allSignatures = type.getNonNullableType().getCallSignatures(); - addSignatureDisplayParts(allSignatures[0], allSignatures); + if (allSignatures.length) { + addSignatureDisplayParts(allSignatures[0], allSignatures); + } } } } @@ -69509,11 +69967,11 @@ var ts; getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, writeFile: function (name, text) { if (ts.fileExtensionIs(name, ".map")) { - ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); + ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name); sourceMapText = text; } else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); + ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name); outputText = text; } }, @@ -70132,6 +70590,7 @@ var ts; 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.SpaceBetweenOpenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 19), 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)); @@ -70203,7 +70662,7 @@ var ts; this.SpaceAfterComma, this.NoSpaceAfterComma, this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, - this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, + this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.SpaceBetweenOpenParens, 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, @@ -71003,7 +71462,6 @@ var ts; } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); - var previousRangeHasError; var previousRange; var previousParent; var previousRangeStartLine; @@ -71339,7 +71797,7 @@ var ts; function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAdded; - if (!rangeHasError && !previousRangeHasError) { + if (!rangeHasError) { if (!previousRange) { var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); @@ -71352,7 +71810,6 @@ var ts; previousRange = range; previousParent = parent; previousRangeStartLine = rangeStart.line; - previousRangeHasError = rangeHasError; return lineAdded; } function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { @@ -71531,6 +71988,32 @@ var ts; } } } + function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, false); } + var tokenStart = tokenAtPosition.getStart(sourceFile); + if (tokenStart <= position && position < tokenAtPosition.getEnd()) { + return undefined; + } + if (precedingToken === undefined) { + precedingToken = ts.findPrecedingToken(position, sourceFile); + } + var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end); + var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); + var commentRanges = trailingRangesOfPreviousToken && leadingCommentRangesOfNextToken ? + trailingRangesOfPreviousToken.concat(leadingCommentRangesOfNextToken) : + trailingRangesOfPreviousToken || leadingCommentRangesOfNextToken; + if (commentRanges) { + for (var _i = 0, commentRanges_1 = commentRanges; _i < commentRanges_1.length; _i++) { + var range = commentRanges_1[_i]; + if ((range.pos < position && position < range.end || + position === range.end && (range.kind === 2 || position === sourceFile.getFullWidth()))) { + return (range.kind === 3 || !onlyMultiLine) && (!predicate || predicate(range)) ? range : undefined; + } + } + } + return undefined; + } + formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { case 152: @@ -71641,11 +72124,27 @@ var ts; return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, true, precedingToken || null); + if (enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 ? column - 1 : column; + } if (!precedingToken) { return getBaseIndentation(options); } var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); - if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) { + if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) { return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; @@ -72050,6 +72549,12 @@ var ts; } return false; } + var ChangeKind; + (function (ChangeKind) { + ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; + ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; + ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + })(ChangeKind || (ChangeKind = {})); function getSeparatorCharacter(separator) { return ts.tokenToString(separator.kind); } @@ -72074,7 +72579,7 @@ var ts; } textChanges.getAdjustedStartPosition = getAdjustedStartPosition; function getAdjustedEndPosition(sourceFile, node, options) { - if (options.useNonAdjustedEndPosition) { + if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { return node.getEnd(); } var end = node.getEnd(); @@ -72094,6 +72599,9 @@ var ts; } return s; } + function getNewlineKind(context) { + return context.newLineCharacter === "\n" ? 1 : 0; + } var ChangeTracker = (function () { function ChangeTracker(newLine, rulesProvider, validator) { this.newLine = newLine; @@ -72103,24 +72611,24 @@ var ts; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromCodeFixContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 : 0, context.rulesProvider); + return new ChangeTracker(getNewlineKind(context), context.rulesProvider); + }; + ChangeTracker.prototype.deleteRange = function (sourceFile, range) { + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); + return this; }; ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, node, options); - this.changes.push({ sourceFile: sourceFile, options: options, range: { pos: startPosition, end: endPosition } }); - return this; - }; - ChangeTracker.prototype.deleteRange = function (sourceFile, range) { - this.changes.push({ sourceFile: sourceFile, range: range }); + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); return this; }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, range: { pos: startPosition, end: endPosition } }); + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); return this; }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { @@ -72156,33 +72664,68 @@ var ts; }; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ sourceFile: sourceFile, range: range, options: options, node: newNode }); + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); return this; }; ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: endPosition } }); - return this; + return this.replaceWithSingle(sourceFile, startPosition, endPosition, newNode, options); }; ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: endPosition } }); + return this.replaceWithSingle(sourceFile, startPosition, endPosition, newNode, options); + }; + ChangeTracker.prototype.replaceWithSingle = function (sourceFile, startPosition, endPosition, newNode, options) { + this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, + sourceFile: sourceFile, + options: options, + node: newNode, + range: { pos: startPosition, end: endPosition } + }); return this; }; + ChangeTracker.prototype.replaceWithMultiple = function (sourceFile, startPosition, endPosition, newNodes, options) { + this.changes.push({ + kind: ChangeKind.ReplaceWithMultipleNodes, + sourceFile: sourceFile, + options: options, + nodes: newNodes, + range: { pos: startPosition, end: endPosition } + }); + return this; + }; + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; + ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, oldNodes[0], options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, ts.lastOrUndefined(oldNodes), options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; + ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { + return this.replaceWithMultiple(sourceFile, range.pos, range.end, newNodes, options); + }; + ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); return this; }; ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, before, options, Position.Start); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: startPosition } }); - return this; + return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, options); }; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { if (options === void 0) { options = {}; } @@ -72192,6 +72735,7 @@ var ts; after.kind === 150) { if (sourceFile.text.charCodeAt(after.end - 1) !== 59) { this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: {}, range: { pos: after.end, end: after.end }, @@ -72200,8 +72744,7 @@ var ts; } } var endPosition = getAdjustedEndPosition(sourceFile, after, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: endPosition, end: endPosition } }); - return this; + return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, options); }; ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) { var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); @@ -72229,10 +72772,10 @@ var ts; startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); } this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: startPos, end: containingList[index + 1].getStart(sourceFile) }, node: newNode, - useIndentationFromFile: true, options: { prefix: prefix, suffix: "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)) @@ -72259,6 +72802,7 @@ var ts; } if (multilineList) { this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: end, end: end }, node: ts.createToken(separator), @@ -72270,6 +72814,7 @@ var ts; insertPos--; } this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: insertPos, end: insertPos }, node: newNode, @@ -72278,6 +72823,7 @@ var ts; } else { this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: end, end: end }, node: newNode, @@ -72317,31 +72863,44 @@ var ts; return ts.createTextSpanFromBounds(change.range.pos, change.range.end); }; ChangeTracker.prototype.computeNewText = function (change, sourceFile) { - if (!change.node) { + var _this = this; + if (change.kind === ChangeKind.Remove) { return ""; } var options = change.options || {}; - var nonFormattedText = getNonformattedText(change.node, sourceFile, this.newLine); - if (this.validator) { - this.validator(nonFormattedText); - } - var formatOptions = this.rulesProvider.getFormatOptions(); + var text; var pos = change.range.pos; var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - var initialIndentation = change.options.indentation !== undefined - ? change.options.indentation - : change.useIndentationFromFile - ? ts.formatting.SmartIndenter.getIndentation(change.range.pos, sourceFile, formatOptions, posStartsLine || (change.options.prefix === this.newLineCharacter)) - : 0; - var delta = change.options.delta !== undefined - ? change.options.delta - : ts.formatting.SmartIndenter.shouldIndentChildNode(change.node) - ? formatOptions.indentSize - : 0; - var text = applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, this.rulesProvider); - text = posStartsLine || change.options.indentation !== undefined ? text : text.replace(/^\s+/, ""); + if (change.kind === ChangeKind.ReplaceWithMultipleNodes) { + var parts = change.nodes.map(function (n) { return _this.getFormattedTextOfNode(n, sourceFile, pos, options); }); + text = parts.join(change.options.nodeSeparator); + } + else { + ts.Debug.assert(change.kind === ChangeKind.ReplaceWithSingleNode, "change.kind === ReplaceWithSingleNode"); + text = this.getFormattedTextOfNode(change.node, sourceFile, pos, options); + } + text = (posStartsLine || options.indentation !== undefined) ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + text + (options.suffix || ""); }; + ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) { + var nonformattedText = getNonformattedText(node, sourceFile, this.newLine); + if (this.validator) { + this.validator(nonformattedText); + } + var formatOptions = this.rulesProvider.getFormatOptions(); + var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; + var initialIndentation = options.indentation !== undefined + ? options.indentation + : (options.useIndentationFromFile !== false) + ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter)) + : 0; + var delta = options.delta !== undefined + ? options.delta + : ts.formatting.SmartIndenter.shouldIndentChildNode(node) + ? (formatOptions.indentSize || 0) + : 0; + return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.rulesProvider); + }; ChangeTracker.normalize = function (changes) { var normalized = ts.stableSort(changes, function (a, b) { return a.range.pos - b.range.pos; }); for (var i = 0; i < normalized.length - 2; i++) { @@ -73319,7 +73878,7 @@ var ts; symbolName = name; } else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { - symbol = checker.getAliasedSymbol(checker.resolveNameAtLocation(token, checker.getJsxNamespace(), 107455)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455)); symbolName = symbol.name; } else { @@ -73403,8 +73962,8 @@ var ts; var namespaceImportDeclaration; var namedImportDeclaration; var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (declaration.kind === 238) { var namedBindings = declaration.importClause && declaration.importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { @@ -73478,14 +74037,53 @@ var ts; : isNamespaceImport ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))])); - var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); + moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); + var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, moduleSpecifierLiteral); if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeAt(sourceFile, getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); } else { changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); } return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getSourceFileImportLocation(node) { + var text = node.text; + var ranges = ts.getLeadingCommentRanges(text, 0); + if (!ranges) + return 0; + var position = 0; + if (ranges.length && ranges[0].kind === 3 && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end + 1; + ranges = ranges.slice(1); + } + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 && ts.isRecognizedTripleSlashComment(node.text, range.pos, range.end)) { + position = range.end + 1; + continue; + } + break; + } + return position; + } + function getSingleQuoteStyleFromExistingImports() { + var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { + if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { + if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { + return node.moduleSpecifier; + } + } + else if (ts.isImportEqualsDeclaration(node)) { + if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { + return node.moduleReference.expression; + } + } + }); + if (firstModuleSpecifier) { + return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39; + } + } function getModuleSpecifierForNewImport() { var fileName = sourceFile.fileName; var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; @@ -73615,7 +74213,8 @@ var ts; (function (States) { States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; States[States["NodeModules"] = 1] = "NodeModules"; - States[States["PackageContent"] = 2] = "PackageContent"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; })(States || (States = {})); var partStart = 0; var partEnd = 0; @@ -73632,15 +74231,21 @@ var ts; } break; case 1: - packageRootIndex = partEnd; - state = 2; - break; case 2: + if (state === 1 && fullPath.charAt(partStart + 1) === "@") { + state = 2; + } + else { + packageRootIndex = partEnd; + state = 3; + } + break; + case 3: if (fullPath.indexOf("/node_modules/", partStart) === partStart) { state = 1; } else { - state = 2; + state = 3; } break; } @@ -73930,206 +74535,1029 @@ var ts; (function (ts) { var refactor; (function (refactor) { - var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); - function getAvailableActions(context) { - if (!ts.isInJavaScriptFile(context.file)) { - return undefined; + var convertFunctionToES6Class; + (function (convertFunctionToES6Class_1) { + var actionName = "convert"; + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions + }; + refactor.registerRefactor(convertFunctionToES6Class); + function getAvailableActions(context) { + if (!ts.isInJavaScriptFile(context.file)) { + return undefined; + } + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start, false); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + if (symbol && (symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { + return [ + { + name: convertFunctionToES6Class.name, + description: convertFunctionToES6Class.description, + actions: [ + { + description: convertFunctionToES6Class.description, + name: actionName + } + ] + } + ]; + } } - var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start, false); - var checker = context.program.getTypeChecker(); - var symbol = checker.getSymbolAtLocation(node); - if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = symbol.valueDeclaration.initializer.symbol; - } - if (symbol && (symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { - return [ - { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, - actions: [ - { - description: convertFunctionToES6Class.description, - name: actionName - } - ] + function getEditsForAction(context, action) { + if (actionName !== action) { + return undefined; + } + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start, false); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 | 3))) { + return undefined; + } + 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 undefined; + } + 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 { + edits: changeTracker.getChanges() + }; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + return; } - ]; - } - } - function getEditsForAction(context, action) { - if (actionName !== action) { - return undefined; - } - var start = context.startPosition; - var sourceFile = context.file; - var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start, false); - var ctorSymbol = checker.getSymbolAtLocation(token); - var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; - var deletedNodes = []; - var deletes = []; - if (!(ctorSymbol.flags & (16 | 3))) { - return undefined; - } - 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); + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); } else { - deleteNode(ctorDeclaration, true); + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); } - newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); - break; - } - if (!newClassDeclaration) { - return undefined; - } - 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 { - edits: 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); }); + 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; + var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + copyComments(assignmentBinaryExpression, method); + return method; + } + 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)]); + } + var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + copyComments(assignmentBinaryExpression, method); + return method; + } + default: { + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + var prop = ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop); + return prop; + } + } + } + } + function copyComments(sourceNode, targetNode) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3) { + pos += 2; + end -= 2; + } + else { + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + }); + } + 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)); + } + var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + return cls; + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); + } + var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + return cls; + } + } + })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var extractMethod; + (function (extractMethod_1) { + var extractMethod = { + name: "Extract Method", + description: ts.Diagnostics.Extract_function.message, + getAvailableActions: getAvailableActions, + getEditsForAction: getEditsForAction, + }; + refactor.registerRefactor(extractMethod); + function getAvailableActions(context) { + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: context.endPosition - context.startPosition }); + var targetRange = rangeToExtract.targetRange; + if (targetRange === undefined) { + return undefined; + } + var extractions = getPossibleExtractions(targetRange, context); + if (extractions === undefined) { + return undefined; + } + var actions = []; + var usedNames = ts.createMap(); + var i = 0; + for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { + var extr = extractions_1[_i]; + if (extr.errors && extr.errors.length) { + continue; + } + var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_function_into_0.message, [extr.scopeDescription]); + if (!usedNames.has(description)) { + usedNames.set(description, true); + actions.push({ + description: description, + name: "scope_" + i + }); + } + i++; + } + if (actions.length === 0) { + return undefined; + } + return [{ + name: extractMethod.name, + description: extractMethod.description, + inlineable: true, + actions: actions + }]; + } + function getEditsForAction(context, actionName) { + var length = context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: length }); + var targetRange = rangeToExtract.targetRange; + var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); + ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); + var index = +parsedIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); + var extractions = getPossibleExtractions(targetRange, context, index); + ts.Debug.assert(extractions !== undefined, "The extraction went missing? How?"); + return ({ edits: extractions[0].changes }); + } + var Messages; + (function (Messages) { + function createMessage(message) { + return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; + } + Messages.CannotExtractFunction = createMessage("Cannot extract function."); + Messages.StatementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.CannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.TypeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.InsufficientSelection = createMessage("Select more than a single identifier."); + Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); + Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + })(Messages || (Messages = {})); + var RangeFacts; + (function (RangeFacts) { + RangeFacts[RangeFacts["None"] = 0] = "None"; + RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn"; + RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis"; + RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; + })(RangeFacts = extractMethod_1.RangeFacts || (extractMethod_1.RangeFacts = {})); + function getRangeToExtract(sourceFile, span) { + var length = span.length || 0; + var start = getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, false), sourceFile, span); + var end = getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); + var declarations = []; + var rangeFacts = RangeFacts.None; + if (!start || !end) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractFunction)] }; + } + if (start.parent !== end.parent) { + var startParent = ts.skipParentheses(start.parent); + var endParent = ts.skipParentheses(end.parent); + if (ts.isBinaryExpression(startParent) && ts.isBinaryExpression(endParent) && ts.isNodeDescendantOf(startParent, endParent)) { + start = end = endParent; + } + else { + return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + } + } + if (start !== end) { + if (!isBlockLike(start.parent)) { + return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + } + var statements = []; + for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement === start || statements.length) { + var errors = checkNode(statement); + if (errors) { + return { errors: errors }; + } + statements.push(statement); + } + if (statement === end) { + break; + } + } + return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } 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 errors = checkRootNode(start) || checkNode(start); + if (errors) { + return { errors: errors }; } - var memberDeclaration = symbol.valueDeclaration; - var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - return; + var range = ts.isStatement(start) + ? [start] + : start.parent && start.parent.kind === 210 + ? [start.parent] + : start; + return { targetRange: { range: range, facts: rangeFacts, declarations: declarations } }; + } + function createErrorResult(sourceFile, start, length, message) { + return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; + } + function checkRootNode(node) { + if (ts.isIdentifier(node)) { + return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; } - 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); + return undefined; + } + function checkForStaticContext(nodeToCheck, containingClass) { + var current = nodeToCheck; + while (current !== containingClass) { + if (current.kind === 149) { + if (ts.hasModifier(current, 32)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 146) { + var ctorOrMethod = ts.getContainingFunction(current); + if (ctorOrMethod.kind === 152) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 151) { + if (ts.hasModifier(current, 32)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + } + current = current.parent; } - switch (assignmentBinaryExpression.right.kind) { - case 186: { - var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); - copyComments(assignmentBinaryExpression, method); - return method; + } + function checkNode(nodeToCheck) { + var PermittedJumps; + (function (PermittedJumps) { + PermittedJumps[PermittedJumps["None"] = 0] = "None"; + PermittedJumps[PermittedJumps["Break"] = 1] = "Break"; + PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; + PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + if (!ts.isStatement(nodeToCheck) && !(ts.isExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; + } + if (ts.isInAmbientContext(nodeToCheck)) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.CannotExtractAmbientBlock)]; + } + var containingClass = ts.getContainingClass(nodeToCheck); + if (containingClass) { + checkForStaticContext(nodeToCheck, containingClass); + } + var errors; + var permittedJumps = 4; + var seenLabels; + visit(nodeToCheck); + return errors; + function visit(node) { + if (errors) { + return true; } - case 187: { - var arrowFunction = assignmentBinaryExpression.right; - var arrowFunctionBody = arrowFunction.body; - var bodyBlock = void 0; - if (arrowFunctionBody.kind === 207) { - bodyBlock = arrowFunctionBody; + if (ts.isDeclaration(node)) { + var declaringNode = (node.kind === 226) ? node.parent.parent : node; + if (ts.hasModifier(declaringNode, 1)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + return true; } - else { - var expression = arrowFunctionBody; - bodyBlock = ts.createBlock([ts.createReturn(expression)]); - } - var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); - copyComments(assignmentBinaryExpression, method); - return method; + declarations.push(node.symbol); } - default: { - if (ts.isSourceFileJavaScript(sourceFile)) { - return; - } - var prop = ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); - copyComments(assignmentBinaryExpression.parent, prop); - return prop; + switch (node.kind) { + case 238: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + return true; + case 97: + if (node.parent.kind === 181) { + var containingClass_1 = ts.getContainingClass(node); + if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + return true; + } + } + else { + rangeFacts |= RangeFacts.UsesThis; + } + break; } + if (!node || ts.isFunctionLike(node) || ts.isClassLike(node)) { + switch (node.kind) { + case 228: + case 229: + if (node.parent.kind === 265 && node.parent.externalModuleIndicator === undefined) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.FunctionWillNotBeVisibleInTheNewScope)); + } + break; + } + return false; + } + var savedPermittedJumps = permittedJumps; + if (node.parent) { + switch (node.parent.kind) { + case 211: + if (node.parent.thenStatement === node || node.parent.elseStatement === node) { + permittedJumps = 0; + } + break; + case 224: + if (node.parent.tryBlock === node) { + permittedJumps = 0; + } + else if (node.parent.finallyBlock === node) { + permittedJumps = 4; + } + break; + case 260: + if (node.parent.block === node) { + permittedJumps = 0; + } + break; + case 257: + if (node.expression !== node) { + permittedJumps |= 1; + } + break; + default: + if (ts.isIterationStatement(node.parent, false)) { + if (node.parent.statement === node) { + permittedJumps |= 1 | 2; + } + } + break; + } + } + switch (node.kind) { + case 169: + case 99: + rangeFacts |= RangeFacts.UsesThis; + break; + case 222: + { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } + case 218: + case 217: + { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } + else { + if (!(permittedJumps & (218 ? 1 : 2))) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } + case 191: + rangeFacts |= RangeFacts.IsAsyncFunction; + break; + case 197: + rangeFacts |= RangeFacts.IsGenerator; + break; + case 219: + if (permittedJumps & 4) { + rangeFacts |= RangeFacts.HasReturn; + } + else { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalReturnStatement)); + } + break; + default: + ts.forEachChild(node, visit); + break; + } + permittedJumps = savedPermittedJumps; } } } - function copyComments(sourceNode, targetNode) { - ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { - if (kind === 3) { - pos += 2; - end -= 2; + extractMethod_1.getRangeToExtract = getRangeToExtract; + function isValidExtractionTarget(node) { + return (node.kind === 228) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + } + function collectEnclosingScopes(range) { + var current = isReadonlyArray(range.range) ? ts.firstOrUndefined(range.range) : range.range; + if (range.facts & RangeFacts.UsesThis) { + var containingClass = ts.getContainingClass(current); + if (containingClass) { + return [containingClass]; + } + } + var start = current; + var scopes = undefined; + while (current) { + if (current !== start && isValidExtractionTarget(current)) { + (scopes = scopes || []).push(current); + } + if (current && current.parent && current.parent.kind === 146) { + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLike(parent); }).parent; } else { - pos += 2; + current = current.parent; } - ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + } + return scopes; + } + extractMethod_1.collectEnclosingScopes = collectEnclosingScopes; + function getPossibleExtractions(targetRange, context, requestedChangesIndex) { + if (requestedChangesIndex === void 0) { requestedChangesIndex = undefined; } + var sourceFile = context.file; + if (targetRange === undefined) { + return undefined; + } + var scopes = collectEnclosingScopes(targetRange); + if (scopes === undefined) { + return undefined; + } + var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + var _a = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker()), target = _a.target, usagesPerScope = _a.usagesPerScope, errorsPerScope = _a.errorsPerScope; + context.cancellationToken.throwIfCancellationRequested(); + if (requestedChangesIndex !== undefined) { + if (errorsPerScope[requestedChangesIndex].length) { + return undefined; + } + return [extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context)]; + } + else { + return scopes.map(function (scope, i) { + var errors = errorsPerScope[i]; + if (errors.length) { + return { + scope: scope, + scopeDescription: getDescriptionForScope(scope), + errors: errors + }; + } + return { scope: scope, scopeDescription: getDescriptionForScope(scope) }; + }); + } + } + extractMethod_1.getPossibleExtractions = getPossibleExtractions; + function getDescriptionForScope(scope) { + if (ts.isFunctionLike(scope)) { + switch (scope.kind) { + case 152: + return "constructor"; + case 186: + return scope.name + ? "function expression " + scope.name.getText() + : "anonymous function expression"; + case 228: + return "function " + scope.name.getText(); + case 187: + return "arrow function"; + case 151: + return "method " + scope.name.getText(); + case 153: + return "get " + scope.name.getText(); + case 154: + return "set " + scope.name.getText(); + } + } + else if (ts.isModuleBlock(scope)) { + return "namespace " + scope.parent.name.getText(); + } + else if (ts.isClassLike(scope)) { + return scope.kind === 229 + ? "class " + scope.name.text + : scope.name.text + ? "class expression " + scope.name.text + : "anonymous class expression"; + } + else if (ts.isSourceFile(scope)) { + return "file '" + scope.fileName + "'"; + } + else { + return "unknown"; + } + } + function getUniqueName(isNameOkay) { + var functionNameText = "newFunction"; + if (isNameOkay(functionNameText)) { + return functionNameText; + } + var i = 1; + while (!isNameOkay(functionNameText = "newFunction_" + i)) { + i++; + } + return functionNameText; + } + function extractFunctionInScope(node, scope, _a, range, context) { + var usagesInScope = _a.usages, substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + var file = scope.getSourceFile(); + var functionNameText = getUniqueName(function (n) { return !file.identifiers.has(n); }); + var isJS = ts.isInJavaScriptFile(scope); + var functionName = ts.createIdentifier(functionNameText); + var functionReference = ts.createIdentifier(functionNameText); + var returnType = undefined; + var parameters = []; + var callArguments = []; + var writes; + usagesInScope.forEach(function (usage, name) { + var typeNode = undefined; + if (!isJS) { + var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + type = checker.getBaseTypeOfLiteralType(type); + typeNode = checker.typeToTypeNode(type, node, ts.NodeBuilderFlags.NoTruncation); + } + var paramDecl = ts.createParameter(undefined, undefined, undefined, name, undefined, typeNode); + parameters.push(paramDecl); + if (usage.usage === 2) { + (writes || (writes = [])).push(usage); + } + callArguments.push(ts.createIdentifier(name)); }); + if (ts.isExpression(node) && !isJS) { + var contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType); + } + var _b = transformFunctionBody(node), body = _b.body, returnValueProperty = _b.returnValueProperty; + var newFunction; + if (ts.isClassLike(scope)) { + var modifiers = isJS ? [] : [ts.createToken(112)]; + if (range.facts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(115)); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + modifiers.push(ts.createToken(120)); + } + newFunction = ts.createMethod(undefined, modifiers, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, undefined, [], parameters, returnType, body); + } + else { + newFunction = ts.createFunctionDeclaration(undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, [], parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + var newNodes = []; + var call = ts.createCall(ts.isClassLike(scope) ? ts.createPropertyAccess(range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.getText()) : ts.createThis(), functionReference) : functionReference, undefined, callArguments); + if (range.facts & RangeFacts.IsGenerator) { + call = ts.createYield(ts.createToken(39), call); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + call = ts.createAwait(call); + } + if (writes) { + if (returnValueProperty) { + newNodes.push(ts.createVariableStatement(undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119))])); + } + var assignments = getPropertyAssignmentsForWrites(writes); + if (returnValueProperty) { + assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); + } + if (assignments.length === 1) { + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + else { + newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58, call))); + } + } + else { + newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58, call))); + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + } + } + else { + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn(call)); + } + else if (isReadonlyArray(range.range)) { + newNodes.push(ts.createStatement(call)); + } + else { + newNodes.push(call); + } + } + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { + nodeSeparator: context.newLineCharacter, + suffix: context.newLineCharacter + }); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); + } + return { + scope: scope, + scopeDescription: getDescriptionForScope(scope), + changes: changeTracker.getChanges() + }; + function getPropertyAssignmentsForWrites(writes) { + return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + } + function generateReturnValueProperty() { + return "__return"; + } + function transformFunctionBody(body) { + if (ts.isBlock(body) && !writes && substitutions.size === 0) { + return { body: ts.createBlock(body.statements, true), returnValueProperty: undefined }; + } + var returnValueProperty; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + if (writes || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (writes && !(range.facts & RangeFacts.HasReturn) && ts.isStatement(body)) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, true), returnValueProperty: undefined }; + } + function visitor(node) { + if (node.kind === 219 && writes) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = generateReturnValueProperty(); + } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); + } + else { + return ts.createReturn(ts.createObjectLiteral(assignments)); + } + } + else { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } + } } - function createClassFromVariableDeclaration(node) { - var initializer = node.initializer; - if (!initializer || initializer.kind !== 186) { + extractMethod_1.extractFunctionInScope = extractFunctionInScope; + function isReadonlyArray(v) { + return ts.isArray(v); + } + function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) + ? { pos: targetRange.range[0].getStart(sourceFile), end: targetRange.range[targetRange.range.length - 1].getEnd() } + : targetRange.range; + } + var Usage; + (function (Usage) { + Usage[Usage["Read"] = 1] = "Read"; + Usage[Usage["Write"] = 2] = "Write"; + })(Usage || (Usage = {})); + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker) { + var usagesPerScope = []; + var substitutionsPerScope = []; + var errorsPerScope = []; + var visibleDeclarationsInExtractedRange = []; + for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { + var _ = scopes_1[_i]; + usagesPerScope.push({ usages: ts.createMap(), substitutions: ts.createMap() }); + substitutionsPerScope.push(ts.createMap()); + errorsPerScope.push([]); + } + var seenUsages = ts.createMap(); + var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); + collectUsages(target); + var _loop_8 = function (i) { + var hasWrite = false; + var readonlyClassPropertyWrite = undefined; + usagesPerScope[i].usages.forEach(function (value) { + if (value.usage === 2) { + hasWrite = true; + if (value.symbol.flags & 106500 && + value.symbol.valueDeclaration && + ts.hasModifier(value.symbol.valueDeclaration, 64)) { + readonlyClassPropertyWrite = value.symbol.valueDeclaration; + } + } + }); + if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { + errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); + } + else if (readonlyClassPropertyWrite && i > 0) { + errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotCombineWritesAndReturns)); + } + }; + for (var i = 0; i < scopes.length; i++) { + _loop_8(i); + } + if (visibleDeclarationsInExtractedRange.length) { + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + function collectUsages(node, valueUsage) { + if (valueUsage === void 0) { valueUsage = 1; } + if (ts.isDeclaration(node) && node.symbol) { + visibleDeclarationsInExtractedRange.push(node.symbol); + } + if (ts.isAssignmentExpression(node)) { + collectUsages(node.left, 2); + collectUsages(node.right); + } + else if (ts.isUnaryExpressionWithWrite(node)) { + collectUsages(node.operand, 2); + } + else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { + ts.forEachChild(node, collectUsages); + } + else if (ts.isIdentifier(node)) { + if (!node.parent) { + return; + } + if (ts.isQualifiedName(node.parent) && node !== node.parent.left) { + return; + } + if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { + return; + } + recordUsage(node, valueUsage, ts.isPartOfTypeNode(node)); + } + else { + ts.forEachChild(node, collectUsages); + } + } + function recordUsage(n, usage, isTypeNode) { + var symbolId = recordUsagebySymbol(n, usage, isTypeNode); + if (symbolId) { + for (var i = 0; i < scopes.length; i++) { + var substitition = substitutionsPerScope[i].get(symbolId); + if (substitition) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitition); + } + } + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + var symbol = checker.getSymbolAtLocation(identifier); + if (!symbol) { + return undefined; + } + var symbolId = ts.getSymbolId(symbol).toString(); + var lastUsage = seenUsages.get(symbolId); + if (lastUsage && lastUsage >= usage) { + return symbolId; + } + seenUsages.set(symbolId, usage); + if (lastUsage) { + for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) { + var perScope = usagesPerScope_1[_i]; + var prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) { + perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + return symbolId; + } + var declInFile = ts.find(symbol.getDeclarations(), function (d) { return d.getSourceFile() === sourceFile; }); + if (!declInFile) { + return undefined; + } + if (ts.rangeContainsRange(enclosingTextRange, declInFile)) { + return undefined; + } + if (targetRange.facts & RangeFacts.IsGenerator && usage === 2) { + for (var _a = 0, errorsPerScope_1 = errorsPerScope; _a < errorsPerScope_1.length; _a++) { + var errors = errorsPerScope_1[_a]; + errors.push(ts.createDiagnosticForNode(identifier, Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators)); + } + } + for (var i = 0; i < scopes.length; i++) { + var scope = scopes[i]; + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + if (resolvedSymbol === symbol) { + continue; + } + if (!substitutionsPerScope[i].has(symbolId)) { + var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) { + substitutionsPerScope[i].set(symbolId, substitution); + } + else if (isTypeName) { + errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + } + else { + usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + } + return symbolId; + } + function checkForUsedDeclarations(node) { + if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) { + return; + } + var sym = checker.getSymbolAtLocation(node); + if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { + for (var _i = 0, errorsPerScope_2 = errorsPerScope; _i < errorsPerScope_2.length; _i++) { + var scope = errorsPerScope_2[_i]; + scope.push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + } + return true; + } + else { + ts.forEachChild(node, checkForUsedDeclarations); + } + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { + if (!symbol) { + return undefined; + } + if (symbol.getDeclarations().some(function (d) { return d.parent === scopeDecl; })) { + return ts.createIdentifier(symbol.name); + } + var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); + if (prefix === undefined) { + return undefined; + } + return isTypeNode ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) : ts.createPropertyAccess(prefix, symbol.name); + } + } + function getParentNodeInSpan(node, file, span) { + if (!node) return undefined; + while (node.parent) { + if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) { + return node; + } + node = node.parent; } - 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)); - } - var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); - return cls; } - function createClassFromFunctionDeclaration(node) { - var memberElements = createClassElementsFromSymbol(ctorSymbol); - if (node.body) { - memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); - } - var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); - return cls; + function spanContainsNode(span, node, file) { + return ts.textSpanContainsPosition(span, node.getStart(file)) && + node.getEnd() <= ts.textSpanEnd(span); } - } + function isExtractableExpression(node) { + switch (node.parent.kind) { + case 264: + return false; + } + switch (node.kind) { + case 9: + return node.parent.kind !== 238 && + node.parent.kind !== 242; + case 198: + case 174: + case 176: + return false; + case 71: + return node.parent.kind !== 176 && + node.parent.kind !== 242 && + node.parent.kind !== 246; + } + return true; + } + function isBlockLike(node) { + switch (node.kind) { + case 207: + case 265: + case 234: + case 257: + return true; + default: + return false; + } + } + })(extractMethod = refactor.extractMethod || (refactor.extractMethod = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); var ts; @@ -74186,12 +75614,14 @@ var ts; ts.scanner.setTextPos(pos); while (pos < end) { var token = ts.scanner.scan(); - ts.Debug.assert(token !== 1); var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); } pos = textPos; + if (token === 1) { + break; + } } return pos; }; @@ -74986,8 +76416,8 @@ var ts; if (program) { var oldSourceFiles = program.getSourceFiles(); var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); } @@ -75009,7 +76439,7 @@ var ts; if (!shouldCreateNewSourceFiles) { var oldSourceFile = program && program.getSourceFileByPath(path); if (oldSourceFile) { - ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + path); + ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path); return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } } @@ -75372,17 +76802,19 @@ var ts; function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var settings = toEditorSettings(options); - if (key === "{") { - return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + if (!ts.isInComment(sourceFile, position)) { + if (key === "{") { + return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "}") { + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === ";") { + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "\n") { + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + } } return []; } @@ -75422,6 +76854,11 @@ var ts; } return true; } + function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine); + return range && ts.createTextSpanFromRange(range); + } function getTodoComments(fileName, descriptors) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -75545,6 +76982,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, @@ -75615,12 +77053,16 @@ var ts; function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(node.name)); - if (name && contextualType) { + return getPropertySymbolsFromType(contextualType, node.name); + } + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + function getPropertySymbolsFromType(type, propName) { + var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); + if (name && type) { var result_10 = []; - var symbol = contextualType.getProperty(name); - if (contextualType.flags & 65536) { - ts.forEach(contextualType.types, function (t) { + var symbol = type.getProperty(name); + if (type.flags & 65536) { + ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { result_10.push(symbol); @@ -75635,7 +77077,7 @@ var ts; } return undefined; } - ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + ts.getPropertySymbolsFromType = getPropertySymbolsFromType; function isArgumentOfElementAccessExpression(node) { return node && node.parent && @@ -76012,6 +77454,10 @@ var ts; var _this = this; return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); }); }; + LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) { + var _this = this; + return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); }); + }; LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options) { var _this = this; return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () { @@ -76307,7 +77753,7 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "2.5"; +var toolsVersion = "2.6"; var ts; (function (ts) { var server; @@ -76323,6 +77769,7 @@ var ts; Arguments.LogFile = "--logFile"; Arguments.EnableTelemetry = "--enableTelemetry"; Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.TypesMapLocation = "--typesMapLocation"; Arguments.NpmLocation = "--npmLocation"; })(Arguments = server.Arguments || (server.Arguments = {})); function hasArgument(argumentName) { @@ -76370,7 +77817,7 @@ var ts; function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), - fileNames: project.getFileNames(true, true), + fileNames: project.getFileNames(true, true).concat(project.getExcludedFiles()), compilerOptions: project.getCompilerOptions(), typeAcquisition: typeAcquisition, unresolvedImports: unresolvedImports, @@ -76470,42 +77917,6 @@ var ts; return []; } server.createSortedArray = createSortedArray; - function toSortedArray(arr, comparer) { - arr.sort(comparer); - return arr; - } - server.toSortedArray = toSortedArray; - function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, compare) { - compare = compare || ts.compareValues; - var newIndex = 0; - var oldIndex = 0; - var newLen = newItems.length; - var oldLen = oldItems.length; - while (newIndex < newLen && oldIndex < oldLen) { - var newItem = newItems[newIndex]; - var oldItem = oldItems[oldIndex]; - var compareResult = compare(newItem, oldItem); - if (compareResult === -1) { - inserted(newItem); - newIndex++; - } - else if (compareResult === 1) { - deleted(oldItem); - oldIndex++; - } - else { - newIndex++; - oldIndex++; - } - } - while (newIndex < newLen) { - inserted(newItems[newIndex++]); - } - while (oldIndex < oldLen) { - deleted(oldItems[oldIndex++]); - } - } - server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; var ThrottledOperations = (function () { function ThrottledOperations(host) { this.host = host; @@ -76550,6 +77961,11 @@ var ts; return GcTimer; }()); server.GcTimer = GcTimer; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +(function (ts) { + var server; + (function (server) { function insertSorted(array, insert, compare) { if (array.length === 0) { array.push(insert); @@ -76575,6 +77991,51 @@ var ts; } } server.removeSorted = removeSorted; + function toSortedArray(arr, comparer) { + arr.sort(comparer); + return arr; + } + server.toSortedArray = toSortedArray; + function toDeduplicatedSortedArray(arr) { + arr.sort(); + ts.filterMutate(arr, isNonDuplicateInSortedArray); + return arr; + } + server.toDeduplicatedSortedArray = toDeduplicatedSortedArray; + function isNonDuplicateInSortedArray(value, index, array) { + return index === 0 || value !== array[index - 1]; + } + function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, compare) { + compare = compare || ts.compareValues; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = compare(newItem, oldItem); + if (compareResult === -1) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1) { + deleted(oldItem); + oldIndex++; + } + else { + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -76588,6 +78049,7 @@ var ts; CommandTypes["Brace"] = "brace"; CommandTypes["BraceFull"] = "brace-full"; CommandTypes["BraceCompletion"] = "braceCompletion"; + CommandTypes["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment"; CommandTypes["Change"] = "change"; CommandTypes["Close"] = "close"; CommandTypes["Completions"] = "completions"; @@ -76679,6 +78141,7 @@ var ts; ModuleKind["System"] = "System"; ModuleKind["ES6"] = "ES6"; ModuleKind["ES2015"] = "ES2015"; + ModuleKind["ESNext"] = "ESNext"; })(ModuleKind = protocol.ModuleKind || (protocol.ModuleKind = {})); var ModuleResolutionKind; (function (ModuleResolutionKind) { @@ -76696,6 +78159,9 @@ var ts; ScriptTarget["ES5"] = "ES5"; ScriptTarget["ES6"] = "ES6"; ScriptTarget["ES2015"] = "ES2015"; + ScriptTarget["ES2016"] = "ES2016"; + ScriptTarget["ES2017"] = "ES2017"; + ScriptTarget["ESNext"] = "ESNext"; })(ScriptTarget = protocol.ScriptTarget || (protocol.ScriptTarget = {})); })(protocol = server.protocol || (server.protocol = {})); })(server = ts.server || (ts.server = {})); @@ -76713,7 +78179,7 @@ var ts; } TextStorage.prototype.getVersion = function () { return this.svc - ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshot().version + ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshotVersion() : "Text-" + this.textVersion; }; TextStorage.prototype.hasScriptVersionCache = function () { @@ -76751,7 +78217,7 @@ var ts; : ts.ScriptSnapshot.fromString(this.getOrLoadText()); }; TextStorage.prototype.getLineInfo = function (line) { - return this.switchToScriptVersionCache().getSnapshot().index.lineNumberToInfo(line); + return this.switchToScriptVersionCache().getLineInfo(line); }; TextStorage.prototype.lineToTextSpan = function (line) { if (!this.svc) { @@ -76760,23 +78226,20 @@ var ts; var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; return ts.createTextSpanFromBounds(start, end); } - var index = this.svc.getSnapshot().index; - var _a = index.lineNumberToInfo(line + 1), lineText = _a.lineText, absolutePosition = _a.absolutePosition; - var len = lineText !== undefined ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition; - return ts.createTextSpan(absolutePosition, len); + return this.svc.lineToTextSpan(line); }; TextStorage.prototype.lineOffsetToPosition = function (line, offset) { if (!this.svc) { return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); } - return this.svc.getSnapshot().index.absolutePositionOfStartOfLine(line) + (offset - 1); + return this.svc.lineOffsetToPosition(line, offset); }; TextStorage.prototype.positionToLineOffset = function (position) { if (!this.svc) { var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; return { line: line + 1, offset: character + 1 }; } - return this.svc.getSnapshot().index.positionToLineOffset(position); + return this.svc.positionToLineOffset(position); }; TextStorage.prototype.getFileText = function (tempFileName) { return this.host.readFile(tempFileName || this.fileName) || ""; @@ -77685,7 +79148,8 @@ var ts; log("Loading " + moduleName + " from " + initialDir + " (resolved to " + resolvedPath + ")"); var result = host.require(resolvedPath, moduleName); if (result.error) { - log("Failed to load module: " + JSON.stringify(result.error)); + var err = result.error.stack || result.error.message || JSON.stringify(result.error); + log("Failed to load module '" + moduleName + "': " + err); return undefined; } return result.module; @@ -77815,7 +79279,7 @@ var ts; return ts.map(this.program.getSourceFiles(), function (sourceFile) { var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); if (!scriptInfo) { - ts.Debug.assert(false, "scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' is missing."); } return scriptInfo; }); @@ -77826,6 +79290,9 @@ var ts; } return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); }; + Project.prototype.getExcludedFiles = function () { + return server.emptyArray; + }; Project.prototype.getFileNames = function (excludeFilesFromExternalLibraries, excludeConfigFiles) { if (!this.program) { return []; @@ -77977,7 +79444,7 @@ var ts; var sourceFile = _b[_a]; this.extractUnresolvedImportsFromSourceFile(sourceFile, result); } - this.lastCachedUnresolvedImportsList = server.toSortedArray(result); + this.lastCachedUnresolvedImportsList = server.toDeduplicatedSortedArray(result); } unresolvedImports = this.lastCachedUnresolvedImportsList; var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, unresolvedImports, hasChanges); @@ -78029,7 +79496,7 @@ var ts; fileWatcher.close(); } }); - var _loop_8 = function (missingFilePath) { + var _loop_9 = function (missingFilePath) { if (!this_1.missingFilesMap.has(missingFilePath)) { var fileWatcher_1 = this_1.projectService.host.watchFile(missingFilePath, function (_filename, eventKind) { if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { @@ -78045,7 +79512,7 @@ var ts; var this_1 = this; for (var _b = 0, missingFilePaths_1 = missingFilePaths; _b < missingFilePaths_1.length; _b++) { var missingFilePath = missingFilePaths_1[_b]; - _loop_8(missingFilePath); + _loop_9(missingFilePath); } } var oldExternalFiles = this.externalFiles || server.emptyArray; @@ -78209,10 +79676,11 @@ var ts; server.Project = Project; var InferredProject = (function (_super) { __extends(InferredProject, _super); - function InferredProject(projectService, documentRegistry, compilerOptions) { + function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath) { var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, true, compilerOptions, false) || this; _this._isJsInferredProject = false; _this.directoriesWatchedForTsconfig = []; + _this.projectRootPath = projectRootPath; return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -78316,7 +79784,7 @@ var ts; } } if (this.projectService.globalPlugins) { - var _loop_9 = function (globalPluginName) { + var _loop_10 = function (globalPluginName) { if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths); @@ -78324,7 +79792,7 @@ var ts; var this_2 = this; for (var _b = 0, _c = this.projectService.globalPlugins; _b < _c.length; _b++) { var globalPluginName = _c[_b]; - _loop_9(globalPluginName); + _loop_10(globalPluginName); } } }; @@ -78447,10 +79915,12 @@ var ts; } this.typeRootsWatchers = undefined; } - this.directoriesWatchedForWildcards.forEach(function (watcher) { - watcher.close(); - }); - this.directoriesWatchedForWildcards = undefined; + if (this.directoriesWatchedForWildcards) { + this.directoriesWatchedForWildcards.forEach(function (watcher) { + watcher.close(); + }); + this.directoriesWatchedForWildcards = undefined; + } this.stopWatchingDirectory(); }; ConfiguredProject.prototype.addOpenRef = function () { @@ -78473,8 +79943,12 @@ var ts; _this.externalProjectName = externalProjectName; _this.compileOnSaveEnabled = compileOnSaveEnabled; _this.projectFilePath = projectFilePath; + _this.excludedFiles = []; return _this; } + ExternalProject.prototype.getExcludedFiles = function () { + return this.excludedFiles; + }; ExternalProject.prototype.getProjectRootPath = function () { if (this.projectFilePath) { return ts.getDirectoryPath(this.projectFilePath); @@ -78680,6 +80154,7 @@ var ts; this.inferredProjects = []; this.configuredProjects = []; this.openFiles = []; + this.compilerOptionsForInferredProjectsPerProjectRoot = ts.createMap(); this.projectToSizeMap = ts.createMap(); this.safelist = defaultTypeSafeList; this.seenProjects = ts.createMap(); @@ -78687,16 +80162,21 @@ var ts; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; this.useSingleInferredProject = opts.useSingleInferredProject; + this.useInferredProjectPerProjectRoot = opts.useInferredProjectPerProjectRoot; this.typingsInstaller = opts.typingsInstaller || server.nullTypingsInstaller; this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds; this.eventHandler = opts.eventHandler; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.host.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.directoryWatchers = new DirectoryWatchers(this); this.throttledOperations = new server.ThrottledOperations(this.host); + if (opts.typesMapLocation) { + this.loadTypesMap(); + } this.typingsInstaller.attach(this); this.typingsCache = new server.TypingsCache(this.typingsInstaller); this.hostConfiguration = { @@ -78719,10 +80199,30 @@ var ts; if (!this.eventHandler) { return; } - this.eventHandler({ + var event = { eventName: server.ProjectLanguageServiceStateEvent, data: { project: project, languageServiceEnabled: languageServiceEnabled } - }); + }; + this.eventHandler(event); + }; + ProjectService.prototype.loadTypesMap = function () { + try { + var fileContent = this.host.readFile(this.typesMapLocation); + if (fileContent === undefined) { + this.logger.info("Provided types map file \"" + this.typesMapLocation + "\" doesn't exist"); + return; + } + var raw = JSON.parse(fileContent); + for (var _i = 0, _a = Object.keys(raw.typesMap); _i < _a.length; _i++) { + var k = _a[_i]; + raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i"); + } + this.safelist = raw.typesMap; + } + catch (e) { + this.logger.info("Error loading types map: " + e); + this.safelist = defaultTypeSafeList; + } }; ProjectService.prototype.updateTypingsForProject = function (response) { var project = this.findProject(response.projectName); @@ -78739,16 +80239,28 @@ var ts; } project.updateGraph(); }; - ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { - this.compilerOptionsForInferredProjects = convertCompilerOptions(projectCompilerOptions); - this.compilerOptionsForInferredProjects.allowNonTsExtensions = true; - this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; - for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - proj.setCompilerOptions(this.compilerOptionsForInferredProjects); - proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; + ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) { + ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); + var compilerOptions = convertCompilerOptions(projectCompilerOptions); + compilerOptions.allowNonTsExtensions = true; + if (projectRootPath) { + this.compilerOptionsForInferredProjectsPerProjectRoot.set(projectRootPath, compilerOptions); } - this.updateProjectGraphs(this.inferredProjects); + else { + this.compilerOptionsForInferredProjects = compilerOptions; + } + var updatedProjects = []; + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var project = _a[_i]; + if (projectRootPath ? + project.projectRootPath === projectRootPath : + !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { + project.setCompilerOptions(compilerOptions); + project.compileOnSaveEnabled = compilerOptions.compileOnSave; + updatedProjects.push(project); + } + } + this.updateProjectGraphs(updatedProjects); }; ProjectService.prototype.stopWatchingDirectory = function (directory) { this.directoryWatchers.stopWatchingDirectory(directory); @@ -78855,10 +80367,11 @@ var ts; } for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { var openFile = _a[_i]; - this.eventHandler({ + var event = { eventName: server.ContextEvent, data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } - }); + }; + this.eventHandler(event); } } this.printProjects(); @@ -78930,7 +80443,7 @@ var ts; break; } }; - ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) { + ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles, projectRootPath) { var externalProject = this.findContainingExternalProject(info.fileName); if (externalProject) { if (addToListOfOpenFiles) { @@ -78955,19 +80468,19 @@ var ts; return; } if (info.containingProjects.length === 0) { - var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info); - if (!this.useSingleInferredProject) { + var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info, projectRootPath); + if (!this.useSingleInferredProject && !inferredProject.projectRootPath) { for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { var f = _c[_b]; if (f.containingProjects.length === 0 || !inferredProject.containsScriptInfo(f)) { continue; } for (var _d = 0, _e = f.containingProjects; _d < _e.length; _d++) { - var fContainingProject = _e[_d]; - if (fContainingProject.projectKind === server.ProjectKind.Inferred && - fContainingProject.isRoot(f) && - fContainingProject !== inferredProject) { - this.removeProject(fContainingProject); + var containingProject = _e[_d]; + if (containingProject.projectKind === server.ProjectKind.Inferred && + containingProject !== inferredProject && + containingProject.isRoot(f)) { + this.removeProject(containingProject); f.attachToProject(inferredProject); } } @@ -79078,31 +80591,32 @@ var ts; return undefined; }; ProjectService.prototype.printProjects = function () { + var _this = this; if (!this.logger.hasLevel(server.LogLevel.verbose)) { return; } this.logger.startGroup(); var counter = 0; - counter = printProjects(this.logger, this.externalProjects, counter); - counter = printProjects(this.logger, this.configuredProjects, counter); - counter = printProjects(this.logger, this.inferredProjects, counter); + var printProjects = function (projects, counter) { + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var project = projects_3[_i]; + project.updateGraph(); + _this.logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); + _this.logger.info(project.filesToString()); + _this.logger.info("-----------------------------------------------"); + counter++; + } + return counter; + }; + counter = printProjects(this.externalProjects, counter); + counter = printProjects(this.configuredProjects, counter); + printProjects(this.inferredProjects, counter); this.logger.info("Open files: "); for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { var rootFile = _a[_i]; this.logger.info("\t" + rootFile.fileName); } this.logger.endGroup(); - function printProjects(logger, projects, counter) { - for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { - var project = projects_3[_i]; - project.updateGraph(); - logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); - logger.info(project.filesToString()); - logger.info("-----------------------------------------------"); - counter++; - } - return counter; - } }; ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { configFileName = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); @@ -79223,10 +80737,11 @@ var ts; if (!this.eventHandler) { return; } - this.eventHandler({ + var event = { eventName: server.ConfigFileDiagEvent, - data: { configFileName: configFileName, diagnostics: diagnostics || [], triggerFile: triggerFile } - }); + data: { configFileName: configFileName, diagnostics: diagnostics || server.emptyArray, triggerFile: triggerFile } + }; + this.eventHandler(event); }; ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { var _this = this; @@ -79375,18 +80890,60 @@ var ts; } return configFileErrors; }; - ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) { + ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (root, projectRootPath) { + if (!this.useInferredProjectPerProjectRoot) { + return undefined; + } + if (projectRootPath) { + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var project = _a[_i]; + if (project.projectRootPath === projectRootPath) { + return project; + } + } + return this.createInferredProject(false, projectRootPath); + } + var bestMatch; + for (var _b = 0, _c = this.inferredProjects; _b < _c.length; _b++) { + var project = _c[_b]; + if (!project.projectRootPath) + continue; + if (!ts.containsPath(project.projectRootPath, root.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) + continue; + if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) + continue; + bestMatch = project; + } + return bestMatch; + }; + ProjectService.prototype.getOrCreateSingleInferredProjectIfEnabled = function () { + if (!this.useSingleInferredProject) { + return undefined; + } + if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === undefined) { + return this.inferredProjects[0]; + } + return this.createInferredProject(true); + }; + ProjectService.prototype.createInferredProject = function (isSingleInferredProject, projectRootPath) { + var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; + var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath); + if (isSingleInferredProject) { + this.inferredProjects.unshift(project); + } + else { + this.inferredProjects.push(project); + } + return project; + }; + ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root, projectRootPath) { var _this = this; - var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length; - var project = useExistingProject - ? this.inferredProjects[0] - : new server.InferredProject(this, this.documentRegistry, this.compilerOptionsForInferredProjects); + var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(root, projectRootPath) || + this.getOrCreateSingleInferredProjectIfEnabled() || + this.createInferredProject(); project.addRoot(root); this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); project.updateGraph(); - if (!useExistingProject) { - this.inferredProjects.push(project); - } return project; }; ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { @@ -79519,7 +81076,7 @@ var ts; project.markAsDirty(); } var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); - this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.assignScriptInfoToInferredProjectIfNecessary(info, true, projectRootPath); this.deleteOrphanScriptInfoNotInAnyProject(); this.printProjects(); return { configFileName: configFileName, configFileErrors: configFileErrors }; @@ -79533,13 +81090,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_10 = function (proj) { + var _loop_11 = function (proj) { var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_10(proj); + _loop_11(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -79644,21 +81201,14 @@ var ts; ProjectService.prototype.resetSafeList = function () { this.safelist = defaultTypeSafeList; }; - ProjectService.prototype.loadSafeList = function (fileName) { - var raw = JSON.parse(this.host.readFile(fileName, "utf-8")); - for (var _i = 0, _a = Object.keys(raw); _i < _a.length; _i++) { - var k = _a[_i]; - raw[k].match = new RegExp(raw[k].match, "i"); - } - this.safelist = raw; - }; ProjectService.prototype.applySafeList = function (proj) { var _this = this; var rootFiles = proj.rootFiles, typeAcquisition = proj.typeAcquisition; var types = (typeAcquisition && typeAcquisition.include) || []; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); - var _loop_11 = function (name) { + var excludedFiles = []; + var _loop_12 = function (name) { var rule = this_3.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -79673,7 +81223,7 @@ var ts; } } if (rule.exclude) { - var _loop_12 = function (exclude) { + var _loop_13 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -79696,7 +81246,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_12(exclude); + _loop_13(exclude); } } else { @@ -79715,10 +81265,23 @@ var ts; var this_3 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_11(name); + _loop_12(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); - proj.rootFiles = proj.rootFiles.filter(function (_file, index) { return !excludeRegexes.some(function (re) { return re.test(normalizedNames[index]); }); }); + var filesToKeep = []; + var _loop_14 = function (i) { + if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { + excludedFiles.push(normalizedNames[i]); + } + else { + filesToKeep.push(proj.rootFiles[i]); + } + }; + for (var i = 0; i < proj.rootFiles.length; i++) { + _loop_14(i); + } + proj.rootFiles = filesToKeep; + return excludedFiles; }; ProjectService.prototype.openExternalProject = function (proj, suppressRefreshOfInferredProjects) { if (suppressRefreshOfInferredProjects === void 0) { suppressRefreshOfInferredProjects = false; } @@ -79726,7 +81289,7 @@ var ts; var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions); proj.typeAcquisition = typeAcquisition; } - this.applySafeList(proj); + var excludedFiles = this.applySafeList(proj); var tsConfigFiles; var rootFiles = []; for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { @@ -79747,6 +81310,7 @@ var ts; var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); var exisingConfigFiles; if (externalProject) { + externalProject.excludedFiles = excludedFiles; if (!tsConfigFiles) { var compilerOptions = convertCompilerOptions(proj.options); if (this.exceededTotalSizeLimitForNonTsFiles(proj.projectFileName, compilerOptions, proj.rootFiles, externalFilePropertyReader)) { @@ -79805,7 +81369,8 @@ var ts; } else { this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition); + var newProj = this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition); + newProj.excludedFiles = excludedFiles; } if (!suppressRefreshOfInferredProjects) { this.refreshInferredProjects(); @@ -79904,20 +81469,16 @@ var ts; var MultistepOperation = (function () { function MultistepOperation(operationHost) { this.operationHost = operationHost; - this.completed = true; } MultistepOperation.prototype.startNew = function (action) { this.complete(); this.requestId = this.operationHost.getCurrentRequestId(); - this.completed = false; this.executeAction(action); }; MultistepOperation.prototype.complete = function () { - if (!this.completed) { - if (this.requestId) { - this.operationHost.sendRequestCompletedEvent(this.requestId); - } - this.completed = true; + if (this.requestId !== undefined) { + this.operationHost.sendRequestCompletedEvent(this.requestId); + this.requestId = undefined; } this.setTimerHandle(undefined); this.setImmediateId(undefined); @@ -80082,6 +81643,9 @@ var ts; _a[server.CommandNames.DocCommentTemplate] = function (request) { return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); }, + _a[server.CommandNames.GetSpanOfEnclosingComment] = function (request) { + return _this.requiredResponse(_this.getSpanOfEnclosingComment(request.arguments)); + }, _a[server.CommandNames.Format] = function (request) { return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); }, @@ -80253,6 +81817,7 @@ var ts; logger: this.logger, cancellationToken: this.cancellationToken, useSingleInferredProject: opts.useSingleInferredProject, + useInferredProjectPerProjectRoot: opts.useInferredProjectPerProjectRoot, typingsInstaller: this.typingsInstaller, throttleWaitMilliseconds: throttleWaitMilliseconds, eventHandler: this.eventHandler, @@ -80279,7 +81844,7 @@ var ts; case server.ContextEvent: var _a = event.data, project_1 = _a.project, fileName_3 = _a.fileName; this.projectService.logger.info("got context event, updating diagnostics for " + fileName_3); - this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, [{ fileName: fileName_3, project: project_1 }], _this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); }); + this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, [{ fileName: fileName_3, project: project_1 }], 100); }); break; case server.ConfigFileDiagEvent: var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; @@ -80387,26 +81952,24 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) { + Session.prototype.updateProjectStructure = function () { var _this = this; - if (ms === void 0) { ms = 1500; } + var ms = 1500; + var seq = this.changeSeq; this.host.setTimeout(function () { - if (matchSeq(seq)) { + if (_this.changeSeq === seq) { _this.projectService.refreshInferredProjects(); } }, ms); }; - Session.prototype.updateErrorCheck = function (next, checkList, seq, matchSeq, ms, followMs, requireOpen) { + Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) { var _this = this; - if (ms === void 0) { ms = 1500; } - if (followMs === void 0) { followMs = 200; } if (requireOpen === void 0) { requireOpen = true; } - if (followMs > ms) { - followMs = ms; - } + var seq = this.changeSeq; + var followMs = Math.min(ms, 200); var index = 0; var checkOne = function () { - if (matchSeq(seq)) { + if (_this.changeSeq === seq) { var checkSpec_1 = checkList[index]; index++; if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { @@ -80420,7 +81983,7 @@ var ts; } } }; - if ((checkList.length > index) && (matchSeq(seq))) { + if (checkList.length > index && this.changeSeq === seq) { next.delay(ms, checkOne); } }; @@ -80498,7 +82061,7 @@ var ts; Session.prototype.getDiagnosticsWorker = function (args, isSemantic, selector, includeLinePosition) { var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { - return []; + return server.emptyArray; } var scriptInfo = project.getScriptInfoForNormalizedPath(file); var diagnostics = selector(project, file); @@ -80512,7 +82075,7 @@ var ts; var position = this.getPosition(args, scriptInfo); var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); if (!definitions) { - return undefined; + return server.emptyArray; } if (simplifiedResult) { return definitions.map(function (def) { @@ -80534,7 +82097,7 @@ var ts; var position = this.getPosition(args, scriptInfo); var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); if (!definitions) { - return undefined; + return server.emptyArray; } return definitions.map(function (def) { var defScriptInfo = project.getScriptInfo(def.fileName); @@ -80550,7 +82113,7 @@ var ts; var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); var implementations = project.getLanguageService().getImplementationAtPosition(file, position); if (!implementations) { - return []; + return server.emptyArray; } if (simplifiedResult) { return implementations.map(function (_a) { @@ -80573,7 +82136,7 @@ var ts; var position = this.getPosition(args, scriptInfo); var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); if (!occurrences) { - return undefined; + return server.emptyArray; } return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan, isInString = occurrence.isInString; @@ -80595,7 +82158,7 @@ var ts; Session.prototype.getSyntacticDiagnosticsSync = function (args) { var configFile = this.getConfigFileAndProject(args).configFile; if (configFile) { - return []; + return server.emptyArray; } return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); }; @@ -80612,7 +82175,7 @@ var ts; var position = this.getPosition(args, scriptInfo); var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); if (!documentHighlights) { - return undefined; + return server.emptyArray; } if (simplifiedResult) { return documentHighlights.map(convertToDocumentHighlightsItem); @@ -80636,7 +82199,7 @@ var ts; } }; Session.prototype.setCompilerOptionsForInferredProjects = function (args) { - this.projectService.setCompilerOptionsForInferredProjects(args.options); + this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); }; Session.prototype.getProjectInfo = function (args) { return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, false); @@ -80698,13 +82261,13 @@ var ts; if (!renameInfo.canRename) { return { info: renameInfo, - locs: [] + locs: server.emptyArray }; } var fileSpans = server.combineProjectOutput(projects, function (project) { var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); if (!renameLocations) { - return []; + return server.emptyArray; } return renameLocations.map(function (location) { var locationScriptInfo = project.getScriptInfo(location.fileName); @@ -80785,7 +82348,7 @@ var ts; var refs = server.combineProjectOutput(projects, function (project) { var references = project.getLanguageService().getReferencesAtPosition(file, position); if (!references) { - return []; + return server.emptyArray; } return references.map(function (ref) { var refScriptInfo = project.getScriptInfo(ref.fileName); @@ -80826,7 +82389,7 @@ var ts; if (this.eventHandler) { this.eventHandler({ eventName: "configFileDiag", - data: { triggerFile: fileName, configFileName: configFileName, diagnostics: configFileErrors || [] } + data: { triggerFile: fileName, configFileName: configFileName, diagnostics: configFileErrors || server.emptyArray } }); } }; @@ -80863,6 +82426,13 @@ var ts; var position = this.getPosition(args, scriptInfo); return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); }; + Session.prototype.getSpanOfEnclosingComment = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var onlyMultiLine = args.onlyMultiLine; + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService(false).getSpanOfEnclosingComment(file, position, onlyMultiLine); + }; Session.prototype.getIndentation = function (args) { var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); @@ -80986,11 +82556,8 @@ var ts; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); var completions = project.getLanguageService().getCompletionsAtPosition(file, position); - if (!completions) { - return undefined; - } if (simplifiedResult) { - return ts.mapDefined(completions.entries, function (entry) { + return ts.mapDefined(completions && completions.entries, function (entry) { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; @@ -81014,7 +82581,7 @@ var ts; var info = this.projectService.getScriptInfo(args.file); var result = []; if (!info) { - return []; + return server.emptyArray; } var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { @@ -81074,11 +82641,10 @@ var ts; return project && { fileName: fileName, project: project }; }); if (checkList.length > 0) { - this.updateErrorCheck(next, checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); + this.updateErrorCheck(next, checkList, delay); } }; Session.prototype.change = function (args) { - var _this = this; var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; if (project) { var scriptInfo = project.getScriptInfoForNormalizedPath(file); @@ -81088,7 +82654,7 @@ var ts; scriptInfo.editContent(start, end, args.insertString); this.changeSeq++; } - this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; }); + this.updateProjectStructure(); } }; Session.prototype.reload = function (args, reqSeq) { @@ -81167,7 +82733,7 @@ var ts; return server.combineProjectOutput(projects, function (project) { var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); if (!navItems) { - return []; + return server.emptyArray; } return navItems.map(function (navItem) { var scriptInfo = project.getScriptInfo(navItem.fileName); @@ -81357,7 +82923,6 @@ var ts; : spans; }; Session.prototype.getDiagnosticsForProject = function (next, delay, fileName) { - var _this = this; var _a = this.getProjectInfoWorker(fileName, undefined, true, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; @@ -81392,7 +82957,7 @@ var ts; fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); - this.updateErrorCheck(next, checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay, 200, false); + this.updateErrorCheck(next, checkList, delay, false); } }; Session.prototype.getCanonicalFileName = function (fileName) { @@ -81499,13 +83064,13 @@ var ts; CharRangeSection[CharRangeSection["Mid"] = 3] = "Mid"; CharRangeSection[CharRangeSection["End"] = 4] = "End"; CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd"; - })(CharRangeSection = server.CharRangeSection || (server.CharRangeSection = {})); + })(CharRangeSection || (CharRangeSection = {})); var EditWalker = (function () { function EditWalker() { this.goSubtree = true; this.lineIndex = new LineIndex(); this.endBranch = []; - this.state = CharRangeSection.Entire; + this.state = 2; this.initialText = ""; this.trailingText = ""; this.lineIndex.root = new LineNode(); @@ -81594,14 +83159,14 @@ var ts; }; EditWalker.prototype.post = function (_relativeStart, _relativeLength, lineCollection) { if (lineCollection === this.lineCollectionAtBranch) { - this.state = CharRangeSection.End; + this.state = 4; } this.stack.pop(); }; EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { var currentNode = this.stack[this.stack.length - 1]; - if ((this.state === CharRangeSection.Entire) && (nodeType === CharRangeSection.Start)) { - this.state = CharRangeSection.Start; + if ((this.state === 2) && (nodeType === 1)) { + this.state = 1; this.branchNode = currentNode; this.lineCollectionAtBranch = lineCollection; } @@ -81614,14 +83179,14 @@ var ts; return new LineNode(); } switch (nodeType) { - case CharRangeSection.PreStart: + case 0: this.goSubtree = false; - if (this.state !== CharRangeSection.End) { + if (this.state !== 4) { currentNode.add(lineCollection); } break; - case CharRangeSection.Start: - if (this.state === CharRangeSection.End) { + case 1: + if (this.state === 4) { this.goSubtree = false; } else { @@ -81630,8 +83195,8 @@ var ts; this.startPath.push(child); } break; - case CharRangeSection.Entire: - if (this.state !== CharRangeSection.End) { + case 2: + if (this.state !== 4) { child = fresh(lineCollection); currentNode.add(child); this.startPath.push(child); @@ -81644,11 +83209,11 @@ var ts; } } break; - case CharRangeSection.Mid: + case 3: this.goSubtree = false; break; - case CharRangeSection.End: - if (this.state !== CharRangeSection.End) { + case 4: + if (this.state !== 4) { this.goSubtree = false; } else { @@ -81659,9 +83224,9 @@ var ts; } } break; - case CharRangeSection.PostEnd: + case 5: this.goSubtree = false; - if (this.state !== CharRangeSection.Start) { + if (this.state !== 1) { currentNode.add(lineCollection); } break; @@ -81671,10 +83236,10 @@ var ts; } }; EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) { - if (this.state === CharRangeSection.Start) { + if (this.state === 1) { this.initialText = ll.text.substring(0, relativeStart); } - else if (this.state === CharRangeSection.Entire) { + else if (this.state === 2) { this.initialText = ll.text.substring(0, relativeStart); this.trailingText = ll.text.substring(relativeStart + relativeLength); } @@ -81695,7 +83260,6 @@ var ts; }; return TextChange; }()); - server.TextChange = TextChange; var ScriptVersionCache = (function () { function ScriptVersionCache() { this.changes = []; @@ -81720,15 +83284,6 @@ var ts; this.getSnapshot(); } }; - ScriptVersionCache.prototype.latest = function () { - return this.versions[this.currentVersionToIndex()]; - }; - ScriptVersionCache.prototype.latestVersion = function () { - if (this.changes.length > 0) { - this.getSnapshot(); - } - return this.currentVersion; - }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; @@ -81741,7 +83296,8 @@ var ts; snap.index.load(lm.lines); this.minVersion = this.currentVersion; }; - ScriptVersionCache.prototype.getSnapshot = function () { + ScriptVersionCache.prototype.getSnapshot = function () { return this._getSnapshot(); }; + ScriptVersionCache.prototype._getSnapshot = function () { var snap = this.versions[this.currentVersionToIndex()]; if (this.changes.length > 0) { var snapIndex = snap.index; @@ -81759,6 +83315,24 @@ var ts; } return snap; }; + ScriptVersionCache.prototype.getSnapshotVersion = function () { + return this._getSnapshot().version; + }; + ScriptVersionCache.prototype.getLineInfo = function (line) { + return this._getSnapshot().index.lineNumberToInfo(line); + }; + ScriptVersionCache.prototype.lineOffsetToPosition = function (line, column) { + return this._getSnapshot().index.absolutePositionOfStartOfLine(line) + (column - 1); + }; + ScriptVersionCache.prototype.positionToLineOffset = function (position) { + return this._getSnapshot().index.positionToLineOffset(position); + }; + ScriptVersionCache.prototype.lineToTextSpan = function (line) { + var index = this._getSnapshot().index; + var _a = index.lineNumberToInfo(line + 1), lineText = _a.lineText, absolutePosition = _a.absolutePosition; + var len = lineText !== undefined ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition; + return ts.createTextSpan(absolutePosition, len); + }; ScriptVersionCache.prototype.getTextChangesBetweenVersions = function (oldVersion, newVersion) { if (oldVersion < newVersion) { if (oldVersion >= this.minVersion) { @@ -81820,7 +83394,6 @@ var ts; }; return LineIndexSnapshot; }()); - server.LineIndexSnapshot = LineIndexSnapshot; var LineIndex = (function () { function LineIndex() { this.checkEdits = false; @@ -82019,18 +83592,18 @@ var ts; var childCharCount = this.children[childIndex].charCount(); var adjustedStart = rangeStart; while (adjustedStart >= childCharCount) { - this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, CharRangeSection.PreStart); + this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0); adjustedStart -= childCharCount; childIndex++; childCharCount = this.children[childIndex].charCount(); } if ((adjustedStart + rangeLength) <= childCharCount) { - if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, CharRangeSection.Entire)) { + if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2)) { return; } } else { - if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, CharRangeSection.Start)) { + if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1)) { return; } var adjustedLength = rangeLength - (childCharCount - adjustedStart); @@ -82038,7 +83611,7 @@ var ts; var child = this.children[childIndex]; childCharCount = child.charCount(); while (adjustedLength > childCharCount) { - if (this.execWalk(0, childCharCount, walkFns, childIndex, CharRangeSection.Mid)) { + if (this.execWalk(0, childCharCount, walkFns, childIndex, 3)) { return; } adjustedLength -= childCharCount; @@ -82046,7 +83619,7 @@ var ts; childCharCount = this.children[childIndex].charCount(); } if (adjustedLength > 0) { - if (this.execWalk(0, adjustedLength, walkFns, childIndex, CharRangeSection.End)) { + if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4)) { return; } } @@ -82055,82 +83628,46 @@ var ts; var clen = this.children.length; if (childIndex < (clen - 1)) { for (var ej = childIndex + 1; ej < clen; ej++) { - this.skipChild(0, 0, ej, walkFns, CharRangeSection.PostEnd); + this.skipChild(0, 0, ej, walkFns, 5); } } } }; LineNode.prototype.charOffsetToLineInfo = function (lineNumberAccumulator, relativePosition) { - var childInfo = this.childFromCharOffset(lineNumberAccumulator, relativePosition); - if (!childInfo.child) { - return { - oneBasedLine: lineNumberAccumulator, - zeroBasedColumn: relativePosition, - lineText: undefined, - }; + if (this.children.length === 0) { + return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: undefined }; } - else if (childInfo.childIndex < this.children.length) { - if (childInfo.child.isLeaf()) { - return { - oneBasedLine: childInfo.lineNumberAccumulator, - zeroBasedColumn: childInfo.relativePosition, - lineText: childInfo.child.text, - }; - } - else { - var lineNode = (childInfo.child); - return lineNode.charOffsetToLineInfo(childInfo.lineNumberAccumulator, childInfo.relativePosition); - } - } - else { - var lineInfo = this.lineNumberToInfo(this.lineCount(), 0); - return { oneBasedLine: this.lineCount(), zeroBasedColumn: lineInfo.leaf.charCount(), lineText: undefined }; - } - }; - LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) { - var childInfo = this.childFromLineNumber(relativeOneBasedLine, positionAccumulator); - if (!childInfo.child) { - return { position: positionAccumulator, leaf: undefined }; - } - else if (childInfo.child.isLeaf()) { - return { position: childInfo.positionAccumulator, leaf: childInfo.child }; - } - else { - var lineNode = (childInfo.child); - return lineNode.lineNumberToInfo(childInfo.relativeOneBasedLine, childInfo.positionAccumulator); - } - }; - LineNode.prototype.childFromLineNumber = function (relativeOneBasedLine, positionAccumulator) { - var child; - var i; - for (i = 0; i < this.children.length; i++) { - child = this.children[i]; - var childLineCount = child.lineCount(); - if (childLineCount >= relativeOneBasedLine) { - break; - } - else { - relativeOneBasedLine -= childLineCount; - positionAccumulator += child.charCount(); - } - } - return { child: child, relativeOneBasedLine: relativeOneBasedLine, positionAccumulator: positionAccumulator }; - }; - LineNode.prototype.childFromCharOffset = function (lineNumberAccumulator, relativePosition) { - var child; - var i; - var len; - for (i = 0, len = this.children.length; i < len; i++) { - child = this.children[i]; + for (var _i = 0, _a = this.children; _i < _a.length; _i++) { + var child = _a[_i]; if (child.charCount() > relativePosition) { - break; + if (child.isLeaf()) { + return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: child.text }; + } + else { + return child.charOffsetToLineInfo(lineNumberAccumulator, relativePosition); + } } else { relativePosition -= child.charCount(); lineNumberAccumulator += child.lineCount(); } } - return { child: child, childIndex: i, relativePosition: relativePosition, lineNumberAccumulator: lineNumberAccumulator }; + var leaf = this.lineNumberToInfo(this.lineCount(), 0).leaf; + return { oneBasedLine: this.lineCount(), zeroBasedColumn: leaf.charCount(), lineText: undefined }; + }; + LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) { + for (var _i = 0, _a = this.children; _i < _a.length; _i++) { + var child = _a[_i]; + var childLineCount = child.lineCount(); + if (childLineCount >= relativeOneBasedLine) { + return child.isLeaf() ? { position: positionAccumulator, leaf: child } : child.lineNumberToInfo(relativeOneBasedLine, positionAccumulator); + } + else { + relativeOneBasedLine -= childLineCount; + positionAccumulator += child.charCount(); + } + } + return { position: positionAccumulator, leaf: undefined }; }; LineNode.prototype.splitAfter = function (childIndex) { var splitNode; @@ -82227,7 +83764,6 @@ var ts; }; return LineNode; }()); - server.LineNode = LineNode; var LineLeaf = (function () { function LineLeaf(text) { this.text = text; @@ -82246,7 +83782,6 @@ var ts; }; return LineLeaf; }()); - server.LineLeaf = LineLeaf; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -82335,14 +83870,15 @@ var ts; Logger.prototype.info = function (s) { this.msg(s, server.Msg.Info); }; + Logger.prototype.err = function (s) { + this.msg(s, server.Msg.Err); + }; Logger.prototype.startGroup = function () { this.inGroup = true; this.firstInGroup = true; }; Logger.prototype.endGroup = function () { this.inGroup = false; - this.seq++; - this.firstInGroup = true; }; Logger.prototype.loggingEnabled = function () { return !!this.logFilename || this.traceToConsole; @@ -82352,24 +83888,32 @@ var ts; }; Logger.prototype.msg = function (s, type) { if (type === void 0) { type = server.Msg.Err; } - if (this.fd >= 0 || this.traceToConsole) { - s = "[" + nowString() + "] " + s + "\n"; + if (!this.canWrite) + return; + s = "[" + nowString() + "] " + s + "\n"; + if (!this.inGroup || this.firstInGroup) { var prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); - if (this.firstInGroup) { - s = prefix + s; - this.firstInGroup = false; - } - if (!this.inGroup) { - this.seq++; - this.firstInGroup = true; - } - if (this.fd >= 0) { - var buf = new Buffer(s); - fs.writeSync(this.fd, buf, 0, buf.length, null); - } - if (this.traceToConsole) { - console.warn(s); - } + s = prefix + s; + } + this.write(s); + if (!this.inGroup) { + this.seq++; + } + }; + Object.defineProperty(Logger.prototype, "canWrite", { + get: function () { + return this.fd >= 0 || this.traceToConsole; + }, + enumerable: true, + configurable: true + }); + Logger.prototype.write = function (s) { + if (this.fd >= 0) { + var buf = new Buffer(s); + fs.writeSync(this.fd, buf, 0, buf.length, null); + } + if (this.traceToConsole) { + console.warn(s); } }; return Logger; @@ -82379,12 +83923,13 @@ var ts; return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); } var NodeTypingsInstaller = (function () { - function NodeTypingsInstaller(telemetryEnabled, logger, host, eventPort, globalTypingsCacheLocation, typingSafeListLocation, npmLocation, newLine) { + function NodeTypingsInstaller(telemetryEnabled, logger, host, eventPort, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, newLine) { var _this = this; this.telemetryEnabled = telemetryEnabled; this.logger = logger; this.globalTypingsCacheLocation = globalTypingsCacheLocation; this.typingSafeListLocation = typingSafeListLocation; + this.typesMapLocation = typesMapLocation; this.npmLocation = npmLocation; this.newLine = newLine; this.installerPidReported = false; @@ -82427,6 +83972,9 @@ var ts; if (this.typingSafeListLocation) { args.push(server.Arguments.TypingSafeListLocation, this.typingSafeListLocation); } + if (this.typesMapLocation) { + args.push(server.Arguments.TypesMapLocation, this.typesMapLocation); + } if (this.npmLocation) { args.push(server.Arguments.NpmLocation, this.npmLocation); } @@ -82530,14 +84078,15 @@ var ts; __extends(IOSession, _super); function IOSession(options) { var _this = this; - var host = options.host, installerEventPort = options.installerEventPort, globalTypingsCacheLocation = options.globalTypingsCacheLocation, typingSafeListLocation = options.typingSafeListLocation, npmLocation = options.npmLocation, canUseEvents = options.canUseEvents; + var host = options.host, installerEventPort = options.installerEventPort, globalTypingsCacheLocation = options.globalTypingsCacheLocation, typingSafeListLocation = options.typingSafeListLocation, typesMapLocation = options.typesMapLocation, npmLocation = options.npmLocation, canUseEvents = options.canUseEvents; var typingsInstaller = disableAutomaticTypingAcquisition ? undefined - : new NodeTypingsInstaller(telemetryEnabled, logger, host, installerEventPort, globalTypingsCacheLocation, typingSafeListLocation, npmLocation, host.newLine); + : new NodeTypingsInstaller(telemetryEnabled, logger, host, installerEventPort, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, host.newLine); _this = _super.call(this, { host: host, cancellationToken: cancellationToken, useSingleInferredProject: useSingleInferredProject, + useInferredProjectPerProjectRoot: useInferredProjectPerProjectRoot, typingsInstaller: typingsInstaller || server.nullTypingsInstaller, byteLength: Buffer.byteLength, hrtime: process.hrtime, @@ -82820,12 +84369,22 @@ var ts; if (localeStr) { ts.validateLocaleAndSetLanguage(localeStr, sys); } + ts.setStackTraceLimit(); var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); + var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(sys.getExecutingFilePath(), "../typesMap.json"); var npmLocation = server.findArgument(server.Arguments.NpmLocation); - var globalPlugins = (server.findArgument("--globalPlugins") || "").split(","); - var pluginProbeLocations = (server.findArgument("--pluginProbeLocations") || "").split(","); + function parseStringArray(argName) { + var arg = server.findArgument(argName); + if (arg === undefined) { + return server.emptyArray; + } + return arg.split(",").filter(function (name) { return name !== ""; }); + } + var globalPlugins = parseStringArray("--globalPlugins"); + var pluginProbeLocations = parseStringArray("--pluginProbeLocations"); var allowLocalPluginLoads = server.hasArgument("--allowLocalPluginLoads"); var useSingleInferredProject = server.hasArgument("--useSingleInferredProject"); + var useInferredProjectPerProjectRoot = server.hasArgument("--useInferredProjectPerProjectRoot"); var disableAutomaticTypingAcquisition = server.hasArgument("--disableAutomaticTypingAcquisition"); var telemetryEnabled = server.hasArgument(server.Arguments.EnableTelemetry); var options = { @@ -82834,9 +84393,11 @@ var ts; installerEventPort: eventPort, canUseEvents: eventPort === undefined, useSingleInferredProject: useSingleInferredProject, + useInferredProjectPerProjectRoot: useInferredProjectPerProjectRoot, disableAutomaticTypingAcquisition: disableAutomaticTypingAcquisition, globalTypingsCacheLocation: getGlobalTypingsCacheLocation(), typingSafeListLocation: typingSafeListLocation, + typesMapLocation: typesMapLocation, npmLocation: npmLocation, telemetryEnabled: telemetryEnabled, logger: logger, @@ -82852,3 +84413,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 fce0d53e63..513d8079a4 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -50,7 +50,7 @@ declare namespace ts { pos: number; end: number; } - enum SyntaxKind { + const enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, SingleLineCommentTrivia = 2, @@ -374,7 +374,7 @@ declare namespace ts { FirstJSDocTagNode = 276, LastJSDocTagNode = 285, } - enum NodeFlags { + const enum NodeFlags { None = 0, Let = 1, Const = 2, @@ -402,7 +402,7 @@ declare namespace ts { ContextFlags = 96256, TypeExcludesFlags = 20480, } - enum ModifierFlags { + const enum ModifierFlags { None = 0, Export = 1, Ambient = 2, @@ -422,7 +422,7 @@ declare namespace ts { TypeScriptModifier = 2270, ExportDefault = 513, } - enum JsxFlags { + const enum JsxFlags { None = 0, IntrinsicNamedElement = 1, IntrinsicIndexedElement = 2, @@ -1175,7 +1175,7 @@ declare namespace ts { interface CatchClause extends Node { kind: SyntaxKind.CatchClause; parent?: TryStatement; - variableDeclaration: VariableDeclaration; + variableDeclaration?: VariableDeclaration; block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; @@ -1432,7 +1432,7 @@ declare namespace ts { jsDocTypeTag?: JSDocTypeTag; isArrayType?: boolean; } - enum FlowFlags { + const enum FlowFlags { Unreachable = 1, Start = 2, BranchLabel = 4, @@ -1452,38 +1452,39 @@ declare namespace ts { interface FlowLock { locked?: boolean; } - interface AfterFinallyFlow extends FlowNode, FlowLock { + interface AfterFinallyFlow extends FlowNodeBase, FlowLock { antecedent: FlowNode; } - interface PreFinallyFlow extends FlowNode { + interface PreFinallyFlow extends FlowNodeBase { antecedent: FlowNode; lock: FlowLock; } - interface FlowNode { + type FlowNode = AfterFinallyFlow | PreFinallyFlow | FlowStart | FlowLabel | FlowAssignment | FlowCondition | FlowSwitchClause | FlowArrayMutation; + interface FlowNodeBase { flags: FlowFlags; id?: number; } - interface FlowStart extends FlowNode { + interface FlowStart extends FlowNodeBase { container?: FunctionExpression | ArrowFunction | MethodDeclaration; } - interface FlowLabel extends FlowNode { + interface FlowLabel extends FlowNodeBase { antecedents: FlowNode[]; } - interface FlowAssignment extends FlowNode { + interface FlowAssignment extends FlowNodeBase { node: Expression | VariableDeclaration | BindingElement; antecedent: FlowNode; } - interface FlowCondition extends FlowNode { + interface FlowCondition extends FlowNodeBase { expression: Expression; antecedent: FlowNode; } - interface FlowSwitchClause extends FlowNode { + interface FlowSwitchClause extends FlowNodeBase { switchStatement: SwitchStatement; clauseStart: number; clauseEnd: number; antecedent: FlowNode; } - interface FlowArrayMutation extends FlowNode { + interface FlowArrayMutation extends FlowNodeBase { node: CallExpression | BinaryExpression; antecedent: FlowNode; } @@ -1607,6 +1608,7 @@ declare namespace ts { getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + getExportSymbolOfSymbol(symbol: Symbol): Symbol; getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; @@ -1684,7 +1686,7 @@ declare namespace ts { reportInaccessibleThisError(): void; reportPrivateInBaseOfClassExpression(propertyName: string): void; } - enum TypeFormatFlags { + const enum TypeFormatFlags { None = 0, WriteArrayAsGenericType = 1, UseTypeOfFunction = 4, @@ -1696,18 +1698,18 @@ declare namespace ts { UseFullyQualifiedType = 256, InFirstTypeArgument = 512, InTypeAlias = 1024, - UseTypeAliasValue = 2048, SuppressAnyReturnType = 4096, AddUndefined = 8192, WriteClassExpressionAsTypeLiteral = 16384, InArrayType = 32768, + UseAliasDefinedOutsideCurrentScope = 65536, } - enum SymbolFormatFlags { + const enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, } - enum TypePredicateKind { + const enum TypePredicateKind { This = 0, Identifier = 1, } @@ -1724,7 +1726,7 @@ declare namespace ts { parameterIndex: number; } type TypePredicate = IdentifierTypePredicate | ThisTypePredicate; - enum SymbolFlags { + const enum SymbolFlags { None = 0, FunctionScopedVariable = 1, BlockScopedVariable = 2, @@ -1794,7 +1796,7 @@ declare namespace ts { exports?: SymbolTable; globalExports?: SymbolTable; } - enum InternalSymbolName { + const enum InternalSymbolName { Call = "__call", Constructor = "__constructor", New = "__new", @@ -1832,7 +1834,7 @@ declare namespace ts { clear(): void; } type SymbolTable = UnderscoreEscapedMap; - enum TypeFlags { + const enum TypeFlags { Any = 1, String = 2, Number = 4, @@ -1889,7 +1891,7 @@ declare namespace ts { } interface EnumType extends Type { } - enum ObjectFlags { + const enum ObjectFlags { Class = 1, Interface = 2, Reference = 4, @@ -1951,7 +1953,7 @@ declare namespace ts { interface IndexType extends Type { type: TypeVariable | UnionOrIntersectionType; } - enum SignatureKind { + const enum SignatureKind { Call = 0, Construct = 1, } @@ -1960,7 +1962,7 @@ declare namespace ts { typeParameters?: TypeParameter[]; parameters: Symbol[]; } - enum IndexKind { + const enum IndexKind { String = 0, Number = 1, } @@ -1969,7 +1971,7 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } - enum InferencePriority { + const enum InferencePriority { NakedTypeVariable = 1, MappedType = 2, ReturnType = 4, @@ -1982,11 +1984,17 @@ declare namespace ts { topLevel: boolean; isFixed: boolean; } - enum InferenceFlags { + const enum InferenceFlags { InferUnionTypes = 1, NoDefault = 2, AnyDefault = 4, } + const enum Ternary { + False = 0, + Maybe = 1, + True = -1, + } + type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary; interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; @@ -2073,6 +2081,7 @@ declare namespace ts { outFile?: string; paths?: MapLike; preserveConstEnums?: boolean; + preserveSymlinks?: boolean; project?: string; reactNamespace?: string; jsxFactory?: string; @@ -2118,13 +2127,13 @@ declare namespace ts { ES2015 = 5, ESNext = 6, } - enum JsxEmit { + const enum JsxEmit { None = 0, Preserve = 1, React = 2, ReactNative = 3, } - enum NewLineKind { + const enum NewLineKind { CarriageReturnLineFeed = 0, LineFeed = 1, } @@ -2132,7 +2141,7 @@ declare namespace ts { line: number; character: number; } - enum ScriptKind { + const enum ScriptKind { Unknown = 0, JS = 1, JSX = 2, @@ -2141,7 +2150,7 @@ declare namespace ts { External = 5, JSON = 6, } - enum ScriptTarget { + const enum ScriptTarget { ES3 = 0, ES5 = 1, ES2015 = 2, @@ -2150,7 +2159,7 @@ declare namespace ts { ESNext = 5, Latest = 5, } - enum LanguageVariant { + const enum LanguageVariant { Standard = 0, JSX = 1, } @@ -2163,7 +2172,7 @@ declare namespace ts { wildcardDirectories?: MapLike; compileOnSave?: boolean; } - enum WatchDirectoryFlags { + const enum WatchDirectoryFlags { None = 0, Recursive = 1, } @@ -2186,8 +2195,13 @@ declare namespace ts { } interface ResolvedModuleFull extends ResolvedModule { extension: Extension; + packageId?: PackageId; } - enum Extension { + interface PackageId { + name: string; + version: string; + } + const enum Extension { Ts = ".ts", Tsx = ".tsx", Dts = ".d.ts", @@ -2229,7 +2243,7 @@ declare namespace ts { text: string; skipTrivia?: (pos: number) => number; } - enum EmitFlags { + const enum EmitFlags { SingleLine = 1, AdviseOnEmitNode = 2, NoSubstitution = 4, @@ -2265,7 +2279,7 @@ declare namespace ts { readonly text: string; readonly priority?: number; } - enum EmitHint { + const enum EmitHint { SourceFile = 0, Expression = 1, IdentifierName = 2, @@ -2326,7 +2340,7 @@ declare namespace ts { } } declare namespace ts { - const versionMajorMinor = "2.5"; + const versionMajorMinor = "2.6"; const version: string; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; @@ -2402,6 +2416,8 @@ declare namespace ts { function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: Node): boolean; + function isEmptyBindingPattern(node: BindingName): node is BindingPattern; + function isEmptyBindingElement(node: BindingElement): boolean; function getCombinedModifierFlags(node: Node): ModifierFlags; function getCombinedNodeFlags(node: Node): NodeFlags; function validateLocaleAndSetLanguage(locale: string, sys: { @@ -2959,8 +2975,8 @@ declare namespace ts { function updateDefaultClause(node: DefaultClause, statements: ReadonlyArray): DefaultClause; function createHeritageClause(token: HeritageClause["token"], types: ReadonlyArray): HeritageClause; function updateHeritageClause(node: HeritageClause, types: ReadonlyArray): HeritageClause; - function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; - function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; + function createCatchClause(variableDeclaration: string | VariableDeclaration | undefined, block: Block): CatchClause; + function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression): PropertyAssignment; function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression): ShorthandPropertyAssignment; @@ -3197,6 +3213,7 @@ declare namespace ts { getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; + getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; @@ -3288,7 +3305,7 @@ declare namespace ts { fileName: string; highlightSpans: HighlightSpan[]; } - enum HighlightSpanKind { + const enum HighlightSpanKind { none = "none", definition = "definition", reference = "reference", @@ -3483,7 +3500,7 @@ declare namespace ts { outputFiles: OutputFile[]; emitSkipped: boolean; } - enum OutputFileType { + const enum OutputFileType { JavaScript = 0, SourceMap = 1, Declaration = 2, @@ -3493,7 +3510,7 @@ declare namespace ts { writeByteOrderMark: boolean; text: string; } - enum EndOfLineState { + const enum EndOfLineState { None = 0, InMultiLineCommentTrivia = 1, InSingleQuoteStringLiteral = 2, @@ -3525,7 +3542,7 @@ declare namespace ts { getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; } - enum ScriptElementKind { + const enum ScriptElementKind { unknown = "", warning = "warning", keyword = "keyword", @@ -3560,7 +3577,7 @@ declare namespace ts { externalModuleName = "external module name", jsxAttribute = "JSX attribute", } - enum ScriptElementKindModifier { + const enum ScriptElementKindModifier { none = "", publicMemberModifier = "public", privateMemberModifier = "private", @@ -3570,7 +3587,7 @@ declare namespace ts { staticModifier = "static", abstractModifier = "abstract", } - enum ClassificationTypeNames { + const enum ClassificationTypeNames { comment = "comment", identifier = "identifier", keyword = "keyword", @@ -3595,7 +3612,7 @@ declare namespace ts { jsxText = "jsx text", jsxAttributeStringLiteralValue = "jsx attribute string literal value", } - enum ClassificationType { + const enum ClassificationType { comment = 1, identifier = 2, keyword = 3, @@ -3687,7 +3704,10 @@ declare namespace ts.server { error: undefined; } | { module: undefined; - error: {}; + error: { + stack?: string; + message?: string; + }; }; interface ServerHost extends System { setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; @@ -3770,6 +3790,7 @@ declare namespace ts.server { const LogFile = "--logFile"; const EnableTelemetry = "--enableTelemetry"; const TypingSafeListLocation = "--typingSafeListLocation"; + const TypesMapLocation = "--typesMapLocation"; const NpmLocation = "--npmLocation"; } function hasArgument(argumentName: string): boolean; @@ -3838,9 +3859,6 @@ declare namespace ts.server { function isInferredProjectName(name: string): boolean; function makeInferredProjectName(counter: number): string; function createSortedArray(): SortedArray; - function toSortedArray(arr: string[]): SortedArray; - function toSortedArray(arr: T[], comparer: Comparer): SortedArray; - function enumerateInsertsAndDeletes(newItems: SortedReadonlyArray, oldItems: SortedReadonlyArray, inserted: (newItem: T) => void, deleted: (oldItem: T) => void, compare?: Comparer): void; class ThrottledOperations { private readonly host; private pendingTimeouts; @@ -3857,13 +3875,12 @@ declare namespace ts.server { scheduleCollect(): void; private static run(self); } - function insertSorted(array: SortedArray, insert: T, compare: Comparer): void; - function removeSorted(array: SortedArray, remove: T, compare: Comparer): void; } declare namespace ts.server.protocol { - enum CommandTypes { + const enum CommandTypes { Brace = "brace", BraceCompletion = "braceCompletion", + GetSpanOfEnclosingComment = "getSpanOfEnclosingComment", Change = "change", Close = "close", Completions = "completions", @@ -3951,6 +3968,13 @@ declare namespace ts.server.protocol { interface TodoCommentsResponse extends Response { body?: TodoComment[]; } + interface SpanOfEnclosingCommentRequest extends FileLocationRequest { + command: CommandTypes.GetSpanOfEnclosingComment; + arguments: SpanOfEnclosingCommentRequestArgs; + } + interface SpanOfEnclosingCommentRequestArgs extends FileLocationRequestArgs { + onlyMultiLine: boolean; + } interface IndentationRequest extends FileLocationRequest { command: CommandTypes.Indentation; arguments: IndentationRequestArgs; @@ -4168,7 +4192,7 @@ declare namespace ts.server.protocol { } interface RenameResponseBody { info: RenameInfo; - locs: SpanGroup[]; + locs: ReadonlyArray; } interface RenameResponse extends Response { body?: RenameResponseBody; @@ -4248,6 +4272,7 @@ declare namespace ts.server.protocol { } interface SetCompilerOptionsForInferredProjectsArgs { options: ExternalProjectCompilerOptions; + projectRootPath?: string; } interface SetCompilerOptionsForInferredProjectsResponse extends Response { } @@ -4603,7 +4628,7 @@ declare namespace ts.server.protocol { interface NavTreeResponse extends Response { body?: NavigationTree; } - enum IndentStyle { + const enum IndentStyle { None = "None", Block = "Block", Smart = "Smart", @@ -4681,6 +4706,7 @@ declare namespace ts.server.protocol { paths?: MapLike; plugins?: PluginImport[]; preserveConstEnums?: boolean; + preserveSymlinks?: boolean; project?: string; reactNamespace?: string; removeComments?: boolean; @@ -4700,13 +4726,13 @@ declare namespace ts.server.protocol { typeRoots?: string[]; [option: string]: CompilerOptionsValue | undefined; } - enum JsxEmit { + const enum JsxEmit { None = "None", Preserve = "Preserve", ReactNative = "ReactNative", React = "React", } - enum ModuleKind { + const enum ModuleKind { None = "None", CommonJS = "CommonJS", AMD = "AMD", @@ -4714,20 +4740,24 @@ declare namespace ts.server.protocol { System = "System", ES6 = "ES6", ES2015 = "ES2015", + ESNext = "ESNext", } - enum ModuleResolutionKind { + const enum ModuleResolutionKind { Classic = "Classic", Node = "Node", } - enum NewLineKind { + const enum NewLineKind { Crlf = "Crlf", Lf = "Lf", } - enum ScriptTarget { + const enum ScriptTarget { ES3 = "ES3", ES5 = "ES5", ES6 = "ES6", ES2015 = "ES2015", + ES2016 = "ES2016", + ES2017 = "ES2017", + ESNext = "ESNext", } } declare namespace ts.server { @@ -4750,6 +4780,7 @@ declare namespace ts.server { host: ServerHost; cancellationToken: ServerCancellationToken; useSingleInferredProject: boolean; + useInferredProjectPerProjectRoot: boolean; typingsInstaller: ITypingsInstaller; byteLength: (buf: string, encoding?: string) => number; hrtime: (start?: number[]) => number[]; @@ -4757,8 +4788,8 @@ declare namespace ts.server { canUseEvents: boolean; eventHandler?: ProjectServiceEventHandler; throttleWaitMilliseconds?: number; - globalPlugins?: string[]; - pluginProbeLocations?: string[]; + globalPlugins?: ReadonlyArray; + pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; } class Session implements EventSender { @@ -4780,13 +4811,13 @@ declare namespace ts.server { private defaultEventHandler(event); logError(err: Error, cmd: string): void; send(msg: protocol.Message): void; - configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: Diagnostic[]): void; + configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ReadonlyArray): 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); - private updateProjectStructure(seq, matchSeq, ms?); - private updateErrorCheck(next, checkList, seq, matchSeq, ms?, followMs?, requireOpen?); + private updateProjectStructure(); + private updateErrorCheck(next, checkList, ms, requireOpen?); private cleanProjects(caption, projects); private cleanup(); private getEncodedSemanticClassifications(args); @@ -4820,6 +4851,7 @@ declare namespace ts.server { private getOutliningSpans(args); private getTodoComments(args); private getDocCommentTemplate(args); + private getSpanOfEnclosingComment(args); private getIndentation(args); private getBreakpointStatement(args); private getNameOrDottedNameSpan(args); @@ -4878,38 +4910,10 @@ declare namespace ts.server { } } declare namespace ts.server { - interface LineCollection { - charCount(): number; - lineCount(): number; - isLeaf(): this is LineLeaf; - walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; - } interface AbsolutePositionAndLineText { absolutePosition: number; lineText: string | undefined; } - enum CharRangeSection { - PreStart = 0, - Start = 1, - Entire = 2, - Mid = 3, - End = 4, - PostEnd = 5, - } - interface ILineIndexWalker { - goSubtree: boolean; - done: boolean; - leaf(relativeStart: number, relativeLength: number, lineCollection: LineLeaf): void; - pre?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): void; - post?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): void; - } - class TextChange { - pos: number; - deleteLen: number; - insertedText: string; - constructor(pos: number, deleteLen: number, insertedText?: string); - getTextChangeRange(): TextChangeRange; - } class ScriptVersionCache { private changes; private readonly versions; @@ -4921,79 +4925,17 @@ declare namespace ts.server { private versionToIndex(version); private currentVersionToIndex(); edit(pos: number, deleteLen: number, insertedText?: string): void; - latest(): LineIndexSnapshot; - latestVersion(): number; reload(script: string): void; - getSnapshot(): LineIndexSnapshot; + getSnapshot(): IScriptSnapshot; + private _getSnapshot(); + getSnapshotVersion(): number; + getLineInfo(line: number): AbsolutePositionAndLineText; + lineOffsetToPosition(line: number, column: number): number; + positionToLineOffset(position: number): protocol.Location; + lineToTextSpan(line: number): TextSpan; getTextChangesBetweenVersions(oldVersion: number, newVersion: number): TextChangeRange; static fromString(script: string): ScriptVersionCache; } - class LineIndexSnapshot implements IScriptSnapshot { - readonly version: number; - readonly cache: ScriptVersionCache; - readonly index: LineIndex; - readonly changesSincePreviousVersion: ReadonlyArray; - constructor(version: number, cache: ScriptVersionCache, index: LineIndex, changesSincePreviousVersion?: ReadonlyArray); - getText(rangeStart: number, rangeEnd: number): string; - getLength(): number; - getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; - } - class LineIndex { - root: LineNode; - checkEdits: boolean; - absolutePositionOfStartOfLine(oneBasedLine: number): number; - positionToLineOffset(position: number): protocol.Location; - private positionToColumnAndLineText(position); - lineNumberToInfo(oneBasedLine: number): AbsolutePositionAndLineText; - load(lines: string[]): void; - walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; - getText(rangeStart: number, rangeLength: number): string; - getLength(): number; - every(f: (ll: LineLeaf, s: number, len: number) => boolean, rangeStart: number, rangeEnd?: number): boolean; - edit(pos: number, deleteLength: number, newText?: string): LineIndex; - private static buildTreeFromBottom(nodes); - static linesFromText(text: string): { - lines: string[]; - lineMap: number[]; - }; - } - class LineNode implements LineCollection { - private readonly children; - totalChars: number; - totalLines: number; - constructor(children?: LineCollection[]); - isLeaf(): boolean; - updateCounts(): void; - private execWalk(rangeStart, rangeLength, walkFns, childIndex, nodeType); - private skipChild(relativeStart, relativeLength, childIndex, walkFns, nodeType); - walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; - charOffsetToLineInfo(lineNumberAccumulator: number, relativePosition: number): { - oneBasedLine: number; - zeroBasedColumn: number; - lineText: string | undefined; - }; - lineNumberToInfo(relativeOneBasedLine: number, positionAccumulator: number): { - position: number; - leaf: LineLeaf | undefined; - }; - private childFromLineNumber(relativeOneBasedLine, positionAccumulator); - private childFromCharOffset(lineNumberAccumulator, relativePosition); - private splitAfter(childIndex); - remove(child: LineCollection): void; - private findChildIndex(child); - insertAt(child: LineCollection, nodes: LineCollection[]): LineNode[]; - add(collection: LineCollection): void; - charCount(): number; - lineCount(): number; - } - class LineLeaf implements LineCollection { - text: string; - constructor(text: string); - isLeaf(): boolean; - walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; - charCount(): number; - lineCount(): number; - } } declare namespace ts.server { class ScriptInfo { @@ -5174,7 +5116,7 @@ declare namespace ts.server { private projectStructureVersion; private projectStateVersion; private typingFiles; - protected projectErrors: Diagnostic[]; + protected projectErrors: ReadonlyArray; typesVersion: number; isNonTsProject(): boolean; isJsOnlyProject(): boolean; @@ -5182,8 +5124,8 @@ declare namespace ts.server { static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {}; constructor(projectName: string, projectKind: ProjectKind, projectService: ProjectService, documentRegistry: DocumentRegistry, hasExplicitListOfFiles: boolean, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean); private setInternalCompilerOptionsForEmittingJsFiles(); - getGlobalProjectErrors(): Diagnostic[]; - getAllProjectErrors(): Diagnostic[]; + getGlobalProjectErrors(): ReadonlyArray; + getAllProjectErrors(): ReadonlyArray; getLanguageService(ensureSynchronized?: boolean): LanguageService; getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; getProjectVersion(): string; @@ -5203,6 +5145,7 @@ declare namespace ts.server { getRootScriptInfos(): ScriptInfo[]; getScriptInfos(): ScriptInfo[]; getFileEmitOutput(info: ScriptInfo, emitOnlyDtsFiles: boolean): EmitOutput; + getExcludedFiles(): ReadonlyArray; getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): NormalizedPath[]; hasConfigFile(configFilePath: NormalizedPath): boolean; getAllEmittableFiles(): string[]; @@ -5228,12 +5171,13 @@ declare namespace ts.server { protected removeRoot(info: ScriptInfo): void; } class InferredProject extends Project { + readonly projectRootPath: string | undefined; private static readonly newName; private _isJsInferredProject; toggleJsInferredProject(isJsInferredProject: boolean): void; setCompilerOptions(options?: CompilerOptions): void; directoriesWatchedForTsconfig: string[]; - constructor(projectService: ProjectService, documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions); + constructor(projectService: ProjectService, documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, projectRootPath?: string); addRoot(info: ScriptInfo): void; removeRoot(info: ScriptInfo): void; getProjectRootPath(): string; @@ -5257,7 +5201,7 @@ declare namespace ts.server { private enablePlugin(pluginConfigEntry, searchPaths); private enableProxy(pluginModuleFactory, configEntry); getProjectRootPath(): string; - setProjectErrors(projectErrors: Diagnostic[]): void; + setProjectErrors(projectErrors: ReadonlyArray): void; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; getTypeAcquisition(): TypeAcquisition; getExternalFiles(): SortedReadonlyArray; @@ -5275,11 +5219,13 @@ declare namespace ts.server { externalProjectName: string; compileOnSaveEnabled: boolean; private readonly projectFilePath; + excludedFiles: ReadonlyArray; private typeAcquisition; constructor(externalProjectName: string, projectService: ProjectService, documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean, projectFilePath?: string); + getExcludedFiles(): ReadonlyArray; getProjectRootPath(): string; getTypeAcquisition(): TypeAcquisition; - setProjectErrors(projectErrors: Diagnostic[]): void; + setProjectErrors(projectErrors: ReadonlyArray): void; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; } } @@ -5301,7 +5247,7 @@ declare namespace ts.server { data: { triggerFile: string; configFileName: string; - diagnostics: Diagnostic[]; + diagnostics: ReadonlyArray; }; } interface ProjectLanguageServiceStateEvent { @@ -5353,11 +5299,15 @@ declare namespace ts.server { types?: string[]; }; } + interface TypesMapFile { + typesMap: SafeList; + simpleMap: string[]; + } function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings; function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; - function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; + function combineProjectOutput(projects: ReadonlyArray, action: (project: Project) => ReadonlyArray, comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; interface HostConfiguration { formatCodeOptions: FormatCodeSettings; hostInfo: string; @@ -5365,19 +5315,21 @@ declare namespace ts.server { } interface OpenConfiguredProjectResult { configFileName?: NormalizedPath; - configFileErrors?: Diagnostic[]; + configFileErrors?: ReadonlyArray; } interface ProjectServiceOptions { host: ServerHost; logger: Logger; cancellationToken: HostCancellationToken; useSingleInferredProject: boolean; + useInferredProjectPerProjectRoot: boolean; typingsInstaller: ITypingsInstaller; eventHandler?: ProjectServiceEventHandler; throttleWaitMilliseconds?: number; - globalPlugins?: string[]; - pluginProbeLocations?: string[]; + globalPlugins?: ReadonlyArray; + pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; + typesMapLocation?: string; } class ProjectService { readonly typingsCache: TypingsCache; @@ -5389,7 +5341,7 @@ declare namespace ts.server { readonly configuredProjects: ConfiguredProject[]; readonly openFiles: ScriptInfo[]; private compilerOptionsForInferredProjects; - private compileOnSaveForInferredProjects; + private compilerOptionsForInferredProjectsPerProjectRoot; private readonly projectToSizeMap; private readonly directoryWatchers; private readonly throttledOperations; @@ -5402,19 +5354,22 @@ declare namespace ts.server { readonly logger: Logger; readonly cancellationToken: HostCancellationToken; readonly useSingleInferredProject: boolean; + readonly useInferredProjectPerProjectRoot: boolean; readonly typingsInstaller: ITypingsInstaller; readonly throttleWaitMilliseconds?: number; private readonly eventHandler?; readonly globalPlugins: ReadonlyArray; readonly pluginProbeLocations: ReadonlyArray; readonly allowLocalPluginLoads: boolean; + readonly typesMapLocation: string | undefined; private readonly seenProjects; constructor(opts: ProjectServiceOptions); ensureInferredProjectsUpToDate_TestOnly(): void; getCompilerOptionsForInferredProjects(): CompilerOptions; onUpdateLanguageServiceStateForProject(project: Project, languageServiceEnabled: boolean): void; + private loadTypesMap(); updateTypingsForProject(response: SetTypings | InvalidateCachedTypings): void; - setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions): void; + setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions, projectRootPath?: string): void; stopWatchingDirectory(directory: string): void; findProject(projectName: string): Project; getDefaultProjectForFile(fileName: NormalizedPath, refreshInferredProjects: boolean): Project; @@ -5431,7 +5386,7 @@ declare namespace ts.server { private onConfigFileAddedForInferredProject(fileName); private getCanonicalFileName(fileName); private removeProject(project); - private assignScriptInfoToInferredProjectIfNecessary(info, addToListOfOpenFiles); + private assignScriptInfoToInferredProjectIfNecessary(info, addToListOfOpenFiles, projectRootPath?); private closeOpenFile(info); private deleteOrphanScriptInfoNotInAnyProject(); private openOrUpdateConfiguredProjectForFile(fileName, projectRootPath?); @@ -5450,7 +5405,10 @@ declare namespace ts.server { private openConfigFile(configFileName, clientFileName?); private updateNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, configFileErrors); private updateConfiguredProject(project); - createInferredProjectWithRootFileIfNecessary(root: ScriptInfo): InferredProject; + private getOrCreateInferredProjectForProjectRootPathIfEnabled(root, projectRootPath); + private getOrCreateSingleInferredProjectIfEnabled(); + private createInferredProject(isSingleInferredProject?, projectRootPath?); + createInferredProjectWithRootFileIfNecessary(root: ScriptInfo, projectRootPath?: string): InferredProject; getOrCreateScriptInfo(uncheckedFileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; getScriptInfo(uncheckedFileName: string): ScriptInfo; watchClosedScriptInfo(info: ScriptInfo): void; @@ -5471,8 +5429,7 @@ declare namespace ts.server { private static readonly filenameEscapeRegexp; private static escapeFilenameForRegex(filename); resetSafeList(): void; - loadSafeList(fileName: string): void; - applySafeList(proj: protocol.ExternalProject): void; + applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; openExternalProject(proj: protocol.ExternalProject, suppressRefreshOfInferredProjects?: boolean): void; } } diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 07c0852235..263796daa7 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -508,11 +508,11 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 2048] = "UseTypeAliasValue"; TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -759,6 +759,12 @@ var ts; InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); var SpecialPropertyAssignmentKind; (function (SpecialPropertyAssignmentKind) { SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; @@ -1155,16 +1161,10 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.5"; + ts.versionMajorMinor = "2.6"; ts.version = ts.versionMajorMinor + ".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() { @@ -1452,10 +1452,9 @@ var ts; ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (f(item)) { - array[outIndex] = item; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; outIndex++; } } @@ -1501,8 +1500,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1572,11 +1571,13 @@ var ts; ts.sameFlatMap = sameFlatMap; function mapDefined(array, mapFn) { var result = []; - for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); - if (mapped !== undefined) { - result.push(mapped); + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } } } return result; @@ -1644,8 +1645,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; if (predicate(v)) { return true; } @@ -1670,8 +1671,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var item = array_6[_i]; + loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -1759,8 +1760,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var v = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -2020,8 +2021,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var value = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -2181,11 +2182,11 @@ var ts; ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { var end = start + length; - Debug.assert(start >= 0, "start must be non-negative, is " + start); - Debug.assert(length >= 0, "length must be non-negative, is " + length); + Debug.assertGreaterThanOrEqual(start, 0); + Debug.assertGreaterThanOrEqual(length, 0); if (file) { - Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); - Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + Debug.assertLessThanOrEqual(start, file.text.length); + Debug.assertLessThanOrEqual(end, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -2394,19 +2395,23 @@ var ts; return normalized; } function normalizePath(path) { + return normalizePathAndParts(path).path; + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { path = normalizeSlashes(path); var rootLength = getRootLength(path); var root = path.substr(0, rootLength); - var normalized = getNormalizedParts(path, rootLength); - if (normalized.length) { - var joinedParts = root + normalized.join(ts.directorySeparator); - return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts; + var parts = getNormalizedParts(path, rootLength); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; } else { - return root; + return { path: root, parts: parts }; } } - ts.normalizePath = normalizePath; + ts.normalizePathAndParts = normalizePathAndParts; function pathEndsWithDirectorySeparator(path) { return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; } @@ -2669,8 +2674,28 @@ var ts; ts.fileExtensionIsOneOf = fileExtensionIsOneOf; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; - var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; - var singleAsteriskRegexFragmentOther = "[^/]*"; + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; function getRegularExpressionForWildcard(specs, basePath, usage) { var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); if (!patterns || !patterns.length) { @@ -2685,18 +2710,16 @@ var ts; if (specs === undefined || specs.length === 0) { return undefined; } - var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; - var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; - var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; return flatMap(specs, function (spec) { - return spec && getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } function isImplicitGlob(lastPathComponent) { return !/[.*?]/.test(lastPathComponent); } ts.isImplicitGlob = isImplicitGlob; - function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; @@ -2728,16 +2751,24 @@ var ts; subpattern += ts.directorySeparator; } if (usage !== "exclude") { + var componentPattern = ""; if (component.charCodeAt(0) === 42) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; component = component.substr(1); } else if (component.charCodeAt(0) === 63) { - subpattern += "[^./]"; + componentPattern += "[^./]"; component = component.substr(1); } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } hasWrittenComponent = true; } @@ -2747,12 +2778,6 @@ var ts; } return subpattern; } - function replaceWildCardCharacterFiles(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); - } - function replaceWildCardCharacterOther(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); - } function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } @@ -2788,19 +2813,19 @@ var ts; var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; files = files.slice().sort(comparer); var _loop_1 = function (current) { - var name = combinePaths(path, current); + var name_1 = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsOneOf(name, extensions)) + if (extensions && !fileExtensionIsOneOf(name_1, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) return "continue"; if (!includeFileRegexes) { - results[0].push(name); + results[0].push(name_1); } else { var includeIndex = findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); if (includeIndex !== -1) { - results[includeIndex].push(name); + results[includeIndex].push(name_1); } } }; @@ -2817,11 +2842,11 @@ var ts; directories = directories.slice().sort(comparer); for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { var current = directories_1[_b]; - var name = combinePaths(path, current); + var name_2 = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { - visitDirectory(name, absoluteName, depth); + visitDirectory(name_2, absoluteName, depth); } } } @@ -2889,14 +2914,7 @@ var ts; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = allSupportedExtensions.slice(0); - for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { - var extInfo = extraFileExtensions_1[_i]; - if (extensions.indexOf(extInfo.extension) === -1) { - extensions.push(extInfo.extension); - } - } - return extensions; + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -3038,12 +3056,37 @@ var ts; function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { if (verboseDebugInfo) { - message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); } fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; function fail(message, stackCrawlMark) { debugger; var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); @@ -3178,6 +3221,10 @@ var ts; Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; function tryGetExtensionFromPath(path) { return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } @@ -3189,6 +3236,12 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; var FileWatcherEventKind; (function (FileWatcherEventKind) { FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; @@ -3238,7 +3291,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -3338,10 +3391,10 @@ var ts; if (entry === "." || entry === "..") { continue; } - var name = ts.combinePaths(path, entry); + var name_3 = ts.combinePaths(path, entry); var stat = void 0; try { - stat = _fs.statSync(name); + stat = _fs.statSync(name_3); } catch (e) { continue; @@ -4064,6 +4117,8 @@ var ts; Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4251,6 +4306,7 @@ var ts; Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -4504,6 +4560,8 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), + Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), }; })(ts || (ts = {})); var ts; @@ -4524,19 +4582,6 @@ var ts; return undefined; } ts.getDeclarationOfKind = getDeclarationOfKind; - function findDeclaration(symbol, predicate) { - var declarations = symbol.declarations; - if (declarations) { - for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { - var declaration = declarations_2[_i]; - if (predicate(declaration)) { - return declaration; - } - } - } - return undefined; - } - ts.findDeclaration = findDeclaration; var stringWriter = createSingleLineStringWriter(); var stringWriterAcquired = false; function createSingleLineStringWriter() { @@ -4599,9 +4644,13 @@ var ts; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && - oldResolution.resolvedFileName === newResolution.resolvedFileName; + oldResolution.resolvedFileName === newResolution.resolvedFileName && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function packageIdIsEqual(a, b) { + return a === b || a && b && a.name === b.name && a.version === b.version; + } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -4666,14 +4715,6 @@ var ts; return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; } ts.nodePosToString = nodePosToString; - function getStartPosOfNode(node) { - return node.pos; - } - ts.getStartPosOfNode = getStartPosOfNode; - function isDefined(value) { - return value !== undefined; - } - ts.isDefined = isDefined; function getEndLinePosition(line, sourceFile) { ts.Debug.assert(line >= 0); var lineStarts = ts.getLineStarts(sourceFile); @@ -4704,6 +4745,25 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + if (text.charCodeAt(commentPos + 1) === 47 && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, comment) { + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 33; + } + ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { if (nodeIsMissing(node)) { return node.pos; @@ -4760,15 +4820,20 @@ var ts; var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return '"' + escapeText(node.text) + '"'; + if (node.singleQuote) { + return "'" + escapeText(node.text, 39) + "'"; + } + else { + return '"' + escapeText(node.text, 34) + '"'; + } case 13: - return "`" + escapeText(node.text) + "`"; + return "`" + escapeText(node.text, 96) + "`"; case 14: - return "`" + escapeText(node.text) + "${"; + return "`" + escapeText(node.text, 96) + "${"; case 15: - return "}" + escapeText(node.text) + "${"; + return "}" + escapeText(node.text, 96) + "${"; case 16: - return "}" + escapeText(node.text) + "`"; + return "}" + escapeText(node.text, 96) + "`"; case 8: return node.text; } @@ -5020,13 +5085,9 @@ var ts; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); + return node.kind !== 10 ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; - function getLeadingCommentRangesOfNodeFromText(node, text) { - return ts.getLeadingCommentRanges(text, node.pos); - } - ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; function getJSDocCommentRanges(node, text) { var commentRanges = (node.kind === 146 || node.kind === 145 || @@ -5034,7 +5095,7 @@ var ts; node.kind === 187 || node.kind === 185) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : - getLeadingCommentRangesOfNodeFromText(node, text); + ts.getLeadingCommentRanges(text, node.pos); return ts.filter(commentRanges, function (comment) { return text.charCodeAt(comment.pos + 1) === 42 && text.charCodeAt(comment.pos + 2) === 42 && @@ -5043,8 +5104,9 @@ var ts; } ts.getJSDocCommentRanges = getJSDocCommentRanges; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; - ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { if (158 <= node.kind && node.kind <= 173) { return true; @@ -5073,23 +5135,23 @@ var ts; case 143: case 179: case 99: - var parent = node.parent; - if (parent.kind === 162) { + var parent_1 = node.parent; + if (parent_1.kind === 162) { return false; } - if (158 <= parent.kind && parent.kind <= 173) { + if (158 <= parent_1.kind && parent_1.kind <= 173) { return true; } - switch (parent.kind) { + switch (parent_1.kind) { case 201: - return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); case 145: - return node === parent.constraint; + return node === parent_1.constraint; case 149: case 148: case 146: case 226: - return node === parent.type; + return node === parent_1.type; case 228: case 186: case 187: @@ -5098,16 +5160,16 @@ var ts; case 150: case 153: case 154: - return node === parent.type; + return node === parent_1.type; case 155: case 156: case 157: - return node === parent.type; + return node === parent_1.type; case 184: - return node === parent.type; + return node === parent_1.type; case 181: case 182: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; case 183: return false; } @@ -5171,9 +5233,9 @@ var ts; return; default: if (ts.isFunctionLike(node)) { - var name = node.name; - if (name && name.kind === 144) { - traverse(name.expression); + var name_4 = node.name; + if (name_4 && name_4.kind === 144) { + traverse(name_4.expression); return; } } @@ -5271,21 +5333,11 @@ var ts; } ts.getPropertyAssignment = getPropertyAssignment; function getContainingFunction(node) { - while (true) { - node = node.parent; - if (!node || ts.isFunctionLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isFunctionLike); } ts.getContainingFunction = getContainingFunction; function getContainingClass(node) { - while (true) { - node = node.parent; - if (!node || ts.isClassLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isClassLike); } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { @@ -5385,13 +5437,13 @@ var ts; function getImmediatelyInvokedFunctionExpression(func) { if (func.kind === 186 || func.kind === 187) { var prev = func; - var parent = func.parent; - while (parent.kind === 185) { - prev = parent; - parent = parent.parent; + var parent_2 = func.parent; + while (parent_2.kind === 185) { + prev = parent_2; + parent_2 = parent_2.parent; } - if (parent.kind === 181 && parent.expression === prev) { - return parent; + if (parent_2.kind === 181 && parent_2.expression === prev) { + return parent_2; } } } @@ -5527,8 +5579,8 @@ var ts; case 8: case 9: case 99: - var parent = node.parent; - switch (parent.kind) { + var parent_3 = node.parent; + switch (parent_3.kind) { case 226: case 146: case 149: @@ -5536,7 +5588,7 @@ var ts; case 264: case 261: case 176: - return parent.initializer === node; + return parent_3.initializer === node; case 210: case 211: case 212: @@ -5546,33 +5598,33 @@ var ts; case 221: case 257: case 223: - return parent.expression === node; + return parent_3.expression === node; case 214: - var forStatement = parent; + var forStatement = parent_3; return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || forStatement.condition === node || forStatement.incrementor === node; case 215: case 216: - var forInStatement = parent; + var forInStatement = parent_3; return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || forInStatement.expression === node; case 184: case 202: - return node === parent.expression; + return node === parent_3.expression; case 205: - return node === parent.expression; + return node === parent_3.expression; case 144: - return node === parent.expression; + return node === parent_3.expression; case 147: case 256: case 255: case 263: return true; case 201: - return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); default: - if (isPartOfExpression(parent)) { + if (isPartOfExpression(parent_3)) { return true; } } @@ -5807,8 +5859,8 @@ var ts; } function getJSDocParameterTags(param) { if (param.name && ts.isIdentifier(param.name)) { - var name_1 = param.name.escapedText; - return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + var name_5 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_5; }); } return undefined; } @@ -6095,14 +6147,14 @@ var ts; ts.getAncestor = getAncestor; function getFileReferenceFromReferencePath(comment, commentRange) { var simpleReferenceRegEx = /^\/\/\/\s*/gim; + var isNoDefaultLibRegEx = new RegExp(defaultLibReferenceRegEx.source, "gim"); if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); - var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); + var refLibResult = !refMatchResult && fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); var match = refMatchResult || refLibResult; if (match) { var pos = commentRange.pos + match[1].length + match[2].length; @@ -6291,10 +6343,6 @@ var ts; return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } ts.getOriginalSourceFile = getOriginalSourceFile; - function getOriginalSourceFiles(sourceFiles) { - return ts.sameMap(sourceFiles, getOriginalSourceFile); - } - ts.getOriginalSourceFiles = getOriginalSourceFiles; var Associativity; (function (Associativity) { Associativity[Associativity["Left"] = 0] = "Left"; @@ -6533,7 +6581,9 @@ var ts; } } ts.createDiagnosticCollection = createDiagnosticCollection; - var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\0": "\\0", "\t": "\\t", @@ -6544,11 +6594,16 @@ var ts; "\n": "\\n", "\\": "\\\\", "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" }); - function escapeString(s) { + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; return s.replace(escapedCharsRegExp, getReplacement); } ts.escapeString = escapeString; @@ -6566,8 +6621,8 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiString(s) { - s = escapeString(s); + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; @@ -6908,7 +6963,7 @@ var ts; var currentDetachedCommentInfo; if (removeComments) { if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); } } else { @@ -6940,9 +6995,8 @@ var ts; } } return currentDetachedCommentInfo; - function isPinnedComment(comment) { - return text.charCodeAt(comment.pos + 1) === 42 && - text.charCodeAt(comment.pos + 2) === 33; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment); } } ts.emitDetachedComments = emitDetachedComments; @@ -7013,9 +7067,13 @@ var ts; } ts.hasModifiers = hasModifiers; function hasModifier(node, flags) { - return (getModifierFlags(node) & flags) !== 0; + return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; function getModifierFlags(node) { if (node.modifierFlagsCache & 536870912) { return node.modifierFlagsCache & ~536870912; @@ -7091,21 +7149,6 @@ var ts; return false; } ts.isDestructuringAssignment = isDestructuringAssignment; - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 71) { - return true; - } - else if (ts.isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } - } function isExpressionWithTypeArgumentsInClassExtendsClause(node) { return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } @@ -7218,72 +7261,6 @@ var ts; return carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; - function isSimpleExpression(node) { - return isSimpleExpressionWorker(node, 0); - } - ts.isSimpleExpression = isSimpleExpression; - function isSimpleExpressionWorker(node, depth) { - if (depth <= 5) { - var kind = node.kind; - if (kind === 9 - || kind === 8 - || kind === 12 - || kind === 13 - || kind === 71 - || kind === 99 - || kind === 97 - || kind === 101 - || kind === 86 - || kind === 95) { - return true; - } - else if (kind === 179) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 180) { - return isSimpleExpressionWorker(node.expression, depth + 1) - && isSimpleExpressionWorker(node.argumentExpression, depth + 1); - } - else if (kind === 192 - || kind === 193) { - return isSimpleExpressionWorker(node.operand, depth + 1); - } - else if (kind === 194) { - return node.operatorToken.kind !== 40 - && isSimpleExpressionWorker(node.left, depth + 1) - && isSimpleExpressionWorker(node.right, depth + 1); - } - else if (kind === 195) { - return isSimpleExpressionWorker(node.condition, depth + 1) - && isSimpleExpressionWorker(node.whenTrue, depth + 1) - && isSimpleExpressionWorker(node.whenFalse, depth + 1); - } - else if (kind === 190 - || kind === 189 - || kind === 188) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 177) { - return node.elements.length === 0; - } - else if (kind === 178) { - return node.properties.length === 0; - } - else if (kind === 181) { - if (!isSimpleExpressionWorker(node.expression, depth + 1)) { - return false; - } - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (!isSimpleExpressionWorker(argument, depth + 1)) { - return false; - } - } - return true; - } - } - return false; - } function formatEnum(value, enumObject, isFlags) { if (value === void 0) { value = 0; } var members = getEnumMembers(enumObject); @@ -7316,10 +7293,10 @@ var ts; } function getEnumMembers(enumObject) { var result = []; - for (var name in enumObject) { - var value = enumObject[name]; + for (var name_6 in enumObject) { + var value = enumObject[name_6]; if (typeof value === "number") { - result.push([value, name]); + result.push([value, name_6]); } } return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); @@ -7352,18 +7329,6 @@ var ts; return formatEnum(flags, ts.ObjectFlags, true); } ts.formatObjectFlags = formatObjectFlags; - function getRangePos(range) { - return range ? range.pos : -1; - } - ts.getRangePos = getRangePos; - function getRangeEnd(range) { - return range ? range.end : -1; - } - ts.getRangeEnd = getRangeEnd; - function movePos(pos, value) { - return ts.positionIsSynthesized(pos) ? -1 : pos + value; - } - ts.movePos = movePos; function createRange(pos, end) { return { pos: pos, end: end }; } @@ -7392,14 +7357,6 @@ var ts; return range.pos === range.end; } ts.isCollapsedRange = isCollapsedRange; - function collapseRangeToStart(range) { - return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); - } - ts.collapseRangeToStart = collapseRangeToStart; - function collapseRangeToEnd(range) { - return isCollapsedRange(range) ? range : moveRangePos(range, range.end); - } - ts.collapseRangeToEnd = collapseRangeToEnd; function createTokenRange(pos, token) { return createRange(pos, pos + ts.tokenToString(token).length); } @@ -7452,22 +7409,6 @@ var ts; function isInitializedVariable(node) { return node.initializer !== undefined; } - function isMergedWithClass(node) { - if (node.symbol) { - for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 229 && declaration !== node) { - return true; - } - } - } - return false; - } - ts.isMergedWithClass = isMergedWithClass; - function isFirstDeclarationOfKind(node, kind) { - return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; - } - ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; function isWatchSet(options) { return options.watch && options.hasOwnProperty("watch"); } @@ -7668,6 +7609,20 @@ var ts; return ts.hasModifier(node, 92) && node.parent.kind === 152 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { while (node && (node.kind === 176 || ts.isBindingPattern(node))) { node = node.parent; @@ -8748,6 +8703,18 @@ var ts; return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 193: + return true; + case 192: + return expr.operator === 43 || + expr.operator === 44; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; function isExpressionKind(kind) { return kind === 195 || kind === 197 @@ -8932,9 +8899,19 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 207; + || isBlockStatement(node); } ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 207) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 224 || node.parent.kind === 260) { + return false; + } + } + return !ts.isFunctionBlock(node); + } function isModuleReference(node) { var kind = node.kind; return kind === 248 @@ -12439,11 +12416,31 @@ var ts; var node = parseTokenNode(); return token() === 23 ? undefined : node; } - function parseLiteralTypeNode() { + function parseLiteralTypeNode(negative) { var node = createNode(173); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(192); + unaryMinusExpression.operator = 38; + nextToken(); + } + var expression; + switch (token()) { + case 9: + case 8: + expression = parseLiteralLikeNode(token()); + break; + case 101: + case 86: + expression = parseTokenNode(); + } + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); } function nextTokenIsNumericLiteral() { return nextToken() === 8; @@ -12475,7 +12472,7 @@ var ts; case 86: return parseLiteralTypeNode(); case 38: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(true) : parseTypeReference(); case 105: case 95: return parseTokenNode(); @@ -12524,6 +12521,7 @@ var ts; case 101: case 86: case 134: + case 39: return true; case 38: return lookAhead(nextTokenIsNumericLiteral); @@ -12842,7 +12840,7 @@ var ts; if (!arrowFunction) { return undefined; } - var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); + var isAsync = ts.hasModifier(arrowFunction, 256); var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 36 || lastToken === 17) @@ -12958,7 +12956,7 @@ var ts; function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(187); node.modifiers = parseModifiersForArrowFunction(); - var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); if (!node.parameters) { return undefined; @@ -13691,7 +13689,7 @@ var ts; parseExpected(89); node.asteriskToken = parseOptionalToken(39); var isGenerator = node.asteriskToken ? 1 : 0; - var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -13916,10 +13914,13 @@ var ts; function parseCatchClause() { var result = createNode(260); parseExpected(74); - if (parseExpected(19)) { + if (parseOptional(19)) { result.variableDeclaration = parseVariableDeclaration(); + parseExpected(20); + } + else { + result.variableDeclaration = undefined; } - parseExpected(20); result.block = parseBlock(false); return finishNode(result); } @@ -14505,8 +14506,8 @@ var ts; return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, undefined); + var name_7 = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -15524,14 +15525,14 @@ var ts; } var typeParameters = createNodeArray(); while (true) { - var name = parseJSDocIdentifierName(); + var name_8 = parseJSDocIdentifierName(); skipWhitespace(); - if (!name) { + if (!name_8) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(145, name.pos); - typeParameter.name = name; + var typeParameter = createNode(145, name_8.pos); + typeParameter.name = name_8; finishNode(typeParameter); typeParameters.push(typeParameter); if (token() === 26) { @@ -15559,11 +15560,11 @@ var ts; parseExpected(22); } while (parseOptional(23)) { - var name = parseJSDocIdentifierName(true); + var name_9 = parseJSDocIdentifierName(true); if (parseOptional(21)) { parseExpected(22); } - entity = createQualifiedName(entity, name); + entity = createQualifiedName(entity, name_9); } return entity; } @@ -15651,8 +15652,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -15724,8 +15725,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -16241,6 +16242,12 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, { name: "sourceRoot", type: "string", @@ -16852,7 +16859,7 @@ var ts; var text = valueExpression.text; if (option && typeof option.type !== "string") { var customOption = option; - if (!customOption.type.has(text)) { + if (!customOption.type.has(text.toLowerCase())) { errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); } } @@ -16930,31 +16937,31 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_3 = function (name) { - if (ts.hasProperty(options, name)) { - if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + var _loop_3 = function (name_10) { + if (ts.hasProperty(options, name_10)) { + if (optionsNameMap.has(name_10) && optionsNameMap.get(name_10).category === ts.Diagnostics.Command_line_Options) { return "continue"; } - var value = options[name]; - var optionDefinition = optionsNameMap.get(name.toLowerCase()); + var value = options[name_10]; + var optionDefinition = optionsNameMap.get(name_10.toLowerCase()); if (optionDefinition) { var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); if (!customTypeMap_1) { - result.set(name, value); + result.set(name_10, value); } else { if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); + result.set(name_10, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); } else { - result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + result.set(name_10, getNameOfCompilerOptionValue(value, customTypeMap_1)); } } } } }; - for (var name in options) { - _loop_3(name); + for (var name_10 in options) { + _loop_3(name_10); } return result; } @@ -17103,12 +17110,10 @@ var ts; } } else { - var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - specs.push(outDir); + excludeSpecs = [outDir]; } - excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; @@ -17359,7 +17364,7 @@ var ts; return value; } else if (typeof option.type !== "string") { - return option.type.get(value); + return option.type.get(typeof value === "string" ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -17434,23 +17439,13 @@ var ts; }; } function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { - var validSpecs = []; - for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { - var spec = specs_1[_i]; - if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); } - else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); - } - else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); - } - else { - validSpecs.push(spec); - } - } - return validSpecs; + return diag === undefined; + }); function createDiagnostic(message, spec) { if (jsonSourceFile && jsonSourceFile.jsonObject) { for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { @@ -17468,6 +17463,17 @@ var ts; return ts.createCompilerDiagnostic(message, spec); } } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); @@ -17590,6 +17596,12 @@ var ts; return compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(undefined, r); + } var Extensions; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; @@ -17605,12 +17617,11 @@ var ts; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } - function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); + function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { if (!ts.hasProperty(jsonContent, fieldName)) { @@ -17704,7 +17715,9 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - resolved = realpath(resolved, host, traceEnabled); + if (!options.preserveSymlinks) { + resolved = realPath(resolved, host, traceEnabled); + } if (traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); } @@ -17821,12 +17834,12 @@ var ts; var commonPrefix = getCommonPrefix(path, resolvedFileName); var current = path; while (true) { - var parent = ts.getDirectoryPath(current); - if (parent === current || directoryPathMap.has(parent)) { + var parent_4 = ts.getDirectoryPath(current); + if (parent_4 === current || directoryPathMap.has(parent_4)) { break; } - directoryPathMap.set(parent, result); - current = parent; + directoryPathMap.set(parent_4, result); + current = parent_4; if (current === commonPrefix) { break; } @@ -18005,7 +18018,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension }; + return { path: path_1, extension: extension, packageId: undefined }; } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -18026,7 +18039,7 @@ var ts; 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(", ")); + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } @@ -18052,16 +18065,22 @@ var ts; trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); - return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks) { + resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + } + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); - return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } } } - function realpath(path, host, traceEnabled) { + function realPath(path, host, traceEnabled) { if (!host.realpath) { return path; } @@ -18087,7 +18106,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return resolvedFromFile; + return noPackageId(resolvedFromFile); } } if (!onlyRecordFailures) { @@ -18105,6 +18124,9 @@ var ts; return !host.directoryExists || host.directoryExists(directoryName); } ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + } function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -18134,9 +18156,9 @@ var ts; case Extensions.JavaScript: return tryExtension(".js") || tryExtension(".jsx"); } - function tryExtension(extension) { - var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, extension: extension }; + function tryExtension(ext) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, ext: ext }; } } function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { @@ -18159,12 +18181,20 @@ var ts; function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + var packageId; if (considerPackageJson) { var packageJsonPath = pathToPackageJson(candidate); if (directoryExists && state.host.fileExists(packageJsonPath)) { - var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var jsonContent = readJson(packageJsonPath, state.host); + if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { + packageId = { name: jsonContent.name, version: jsonContent.version }; + } + var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); if (fromPackageJson) { - return fromPackageJson; + return withPackageId(packageId, fromPackageJson); } } else { @@ -18174,13 +18204,10 @@ var ts; failedLookupLocations.push(packageJsonPath); } } - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } - function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); if (!file) { return undefined; } @@ -18196,11 +18223,15 @@ var ts; } } var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + if (result) { + ts.Debug.assert(result.packageId === undefined); + return { path: result.path, ext: result.extension }; + } } function resolvedIfExtensionMatches(extensions, path) { - var extension = ts.tryGetExtensionFromPath(path); - return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; } function extensionIsOk(extensions, extension) { switch (extensions) { @@ -18217,7 +18248,7 @@ var ts; } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { @@ -18291,7 +18322,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); } - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -18302,7 +18333,7 @@ var ts; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -18314,7 +18345,7 @@ var ts; return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, false, state)); }); if (resolved_3) { return resolved_3; @@ -18325,7 +18356,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, false, state)); } } } @@ -18976,40 +19007,23 @@ var ts; return antecedent; } setFlowNodeReferenced(antecedent); - return { - flags: flags, - expression: expression, - antecedent: antecedent - }; + return { flags: flags, expression: expression, antecedent: antecedent }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); - return { - flags: 128, - switchStatement: switchStatement, - clauseStart: clauseStart, - clauseEnd: clauseEnd, - antecedent: antecedent - }; + return { flags: 128, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { setFlowNodeReferenced(antecedent); - return { - flags: 16, - antecedent: antecedent, - node: node - }; + return { flags: 16, antecedent: antecedent, node: node }; } function createFlowArrayMutation(antecedent, node) { setFlowNodeReferenced(antecedent); - return { - flags: 256, - antecedent: antecedent, - node: node - }; + var res = { flags: 256, antecedent: antecedent, node: node }; + return res; } function finishFlowLabel(flow) { var antecedents = flow.antecedents; @@ -20107,12 +20121,12 @@ var ts; return; } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { + var parent_5 = node.parent; + if (!ts.isExternalModule(parent_5)) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_1.isDeclarationFile) { + if (!parent_5.isDeclarationFile) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -20477,7 +20491,6 @@ var ts; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); var name = node.name; var initializer = node.initializer; var dotDotDotToken = node.dotDotDotToken; @@ -20487,7 +20500,7 @@ var ts; || ts.isThisIdentifier(name)) { transformFlags |= 3; } - if (modifierFlags & 92) { + if (ts.hasModifier(node, 92)) { transformFlags |= 3 | 262144; } if (subtreeFlags & 1048576) { @@ -20516,8 +20529,7 @@ var ts; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 2) { + if (ts.hasModifier(node, 2)) { transformFlags = 3; } else { @@ -20563,7 +20575,10 @@ var ts; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + if (!node.variableDeclaration) { + transformFlags |= 8; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; @@ -20727,9 +20742,8 @@ var ts; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; - var modifierFlags = ts.getModifierFlags(node); var declarationListTransformFlags = node.declarationList.transformFlags; - if (modifierFlags & 2) { + if (ts.hasModifier(node, 2)) { transformFlags = 3; } else { @@ -21028,6 +21042,167 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = ts.createMap(); + var visitedSymbols = ts.createMap(); + return { + walkType: function (type) { + visitedTypes.clear(); + visitedSymbols.clear(); + visitType(type); + return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + }, + walkSymbol: function (symbol) { + visitedTypes.clear(); + visitedSymbols.clear(); + visitSymbol(symbol); + return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + }, + }; + function visitType(type) { + if (!type) { + return; + } + var typeIdString = type.id.toString(); + if (visitedTypes.has(typeIdString)) { + return; + } + visitedTypes.set(typeIdString, type); + var shouldBail = visitSymbol(type.symbol); + if (shouldBail) + return; + if (type.flags & 32768) { + var objectType = type; + var objectFlags = objectType.objectFlags; + if (objectFlags & 4) { + visitTypeReference(type); + } + if (objectFlags & 32) { + visitMappedType(type); + } + if (objectFlags & (1 | 2)) { + visitInterfaceType(type); + } + if (objectFlags & (8 | 16)) { + visitObjectType(objectType); + } + } + if (type.flags & 16384) { + visitTypeParameter(type); + } + if (type.flags & 196608) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 262144) { + visitIndexType(type); + } + if (type.flags & 524288) { + visitIndexedAccessType(type); + } + } + function visitTypeList(types) { + if (!types) { + return; + } + for (var i = 0; i < types.length; i++) { + visitType(types[i]); + } + } + function visitTypeReference(type) { + visitType(type.target); + visitTypeList(type.typeArguments); + } + function visitTypeParameter(type) { + visitType(getConstraintFromTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + visitTypeList(type.types); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + if (signature.typePredicate) { + visitType(signature.typePredicate.type); + } + visitTypeList(signature.typeParameters); + for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + visitTypeList(interfaceT.typeParameters); + visitTypeList(getBaseTypes(interfaceT)); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + var stringIndexType = getIndexTypeOfStructuredType(type, 0); + visitType(stringIndexType); + var numberIndexType = getIndexTypeOfStructuredType(type, 1); + visitType(numberIndexType); + var resolved = resolveStructuredTypeMembers(type); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + visitSignature(signature); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + visitSignature(signature); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return; + } + var symbolIdString = ts.getSymbolId(symbol).toString(); + if (visitedSymbols.has(symbolIdString)) { + return; + } + visitedSymbols.set(symbolIdString, symbol); + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); + if (symbol.flags & 1952) { + symbol.exports.forEach(visitSymbol); + } + ts.forEach(symbol.declarations, function (d) { + if (d.type && d.type.kind === 162) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); +var ts; (function (ts) { var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; @@ -21138,6 +21313,9 @@ var ts; node = ts.getParseTreeNode(node, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, + getExportSymbolOfSymbol: function (symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, getTypeAtLocation: function (node) { node = ts.getParseTreeNode(node); return node ? getTypeOfNode(node) : unknownType; @@ -21200,6 +21378,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); @@ -21220,11 +21399,10 @@ var ts; getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, getBaseConstraintOfType: getBaseConstraintOfType, - getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, - resolveNameAtLocation: function (location, name, meaning) { - location = ts.getParseTreeNode(location); - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, ts.escapeLeadingUnderscores(name)); + resolveName: function (name, location, meaning) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined); }, + getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -21707,7 +21885,10 @@ var ts; } return true; } - if (usage.parent.kind === 246) { + if (usage.parent.kind === 246 || (usage.parent.kind === 243 && usage.parent.isExportEquals)) { + return true; + } + if (usage.kind === 243 && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -21737,13 +21918,13 @@ var ts; current.parent.kind === 149 && current.parent.initializer === current; if (initializerOfProperty) { - if (ts.getModifierFlags(current.parent) & 32) { + if (ts.hasModifier(current.parent, 32)) { if (declaration.kind === 151) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 149 && !(ts.getModifierFlags(declaration) & 32); + var isDeclarationInstanceProperty = declaration.kind === 149 && !ts.hasModifier(declaration, 32); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -21823,7 +22004,7 @@ var ts; break; case 149: case 148: - if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 107455)) { @@ -21840,7 +22021,7 @@ var ts; result = undefined; break; } - if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { + if (lastLocation && ts.hasModifier(lastLocation, 32)) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; } @@ -21854,6 +22035,17 @@ var ts; } } break; + case 201: + if (lastLocation === location.expression && location.parent.token === 85) { + var container = location.parent.parent; + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 793064))) { + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return undefined; + } + } + break; case 144: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 230) { @@ -21900,7 +22092,7 @@ var ts; lastLocation = location; location = location.parent; } - if (result && nameNotFoundMessage && noUnusedIdentifiers) { + if (result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { result.isReferenced = true; } if (!result) { @@ -21981,7 +22173,7 @@ var ts; error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); return true; } - if (location === container && !(ts.getModifierFlags(location) & 32)) { + if (location === container && !ts.hasModifier(location, 32)) { var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); @@ -22016,14 +22208,14 @@ var ts; function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { if (meaning === 1920) { var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); - var parent = errorLocation.parent; + var parent_6 = errorLocation.parent; if (symbol) { - if (ts.isQualifiedName(parent)) { - ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); - var propName = parent.right.escapedText; + if (ts.isQualifiedName(parent_6)) { + ts.Debug.assert(parent_6.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent_6.right.escapedText; var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); if (propType) { - error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + error(parent_6, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); return true; } } @@ -22161,28 +22353,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { - var name = specifier.propertyName || specifier.name; - if (name.escapedText) { + var name_11 = specifier.propertyName || specifier.name; + if (name_11.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_11.escapedText); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.escapedText); } symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); - var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); - if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { + var symbolFromModule = getExportOfModule(targetSymbol, name_11.escapedText, dontResolveAlias); + if (!symbolFromModule && allowSyntheticDefaultImports && name_11.escapedText === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); + error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_11)); } return symbol; } @@ -22367,7 +22559,6 @@ var ts; if (ambientModule) { return ambientModule; } - var isRelative = ts.isExternalModuleNameRelative(moduleReference); var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); @@ -22386,7 +22577,7 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule && resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -22609,19 +22800,19 @@ var ts; } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; - for (var location = enclosingDeclaration; location; location = location.parent) { - if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + for (var location_1 = enclosingDeclaration; location_1; location_1 = location_1.parent) { + if (location_1.locals && !isGlobalSourceFile(location_1)) { + if (result = callback(location_1.locals)) { return result; } } - switch (location.kind) { + switch (location_1.kind) { case 265: - if (!ts.isExternalOrCommonJsModule(location)) { + if (!ts.isExternalOrCommonJsModule(location_1)) { break; } case 233: - if (result = callback(getSymbolOfNode(location).exports)) { + if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; @@ -22721,6 +22912,10 @@ var ts; } return false; } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064, false); + return access.accessibility === 0; + } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; @@ -22776,7 +22971,7 @@ var ts; if (!isDeclarationVisible(declaration)) { var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(ts.getModifierFlags(anyImportSyntax) & 1) && + !ts.hasModifier(anyImportSyntax, 1) && isDeclarationVisible(anyImportSyntax.parent)) { if (shouldComputeAliasToMakeVisible) { getNodeLinks(declaration).isVisible = true; @@ -22927,8 +23122,8 @@ var ts; return ts.createTypeReferenceNode(enumLiteralName, undefined); } if (type.flags & 272) { - var name = symbolToName(type.symbol, context, 793064, false); - return ts.createTypeReferenceNode(name, undefined); + var name_12 = symbolToName(type.symbol, context, 793064, false); + return ts.createTypeReferenceNode(name_12, undefined); } if (type.flags & (32)) { return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); @@ -22971,14 +23166,13 @@ var ts; return typeReferenceToTypeNode(type); } if (type.flags & 16384 || objectFlags & 3) { - var name = symbolToName(type.symbol, context, 793064, false); - return ts.createTypeReferenceNode(name, undefined); + var name_13 = symbolToName(type.symbol, context, 793064, false); + return ts.createTypeReferenceNode(name_13, undefined); } - if (!inTypeAlias && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064, false).accessibility === 0) { - var name = symbolToTypeReferenceName(type.aliasSymbol); + if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { + var name_14 = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - return ts.createTypeReferenceNode(name, typeArgumentNodes); + return ts.createTypeReferenceNode(name_14, typeArgumentNodes); } if (type.flags & (65536 | 131072)) { var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; @@ -23050,8 +23244,8 @@ var ts; return createTypeNodeFromObjectType(type); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isStaticMethodSymbol = !!(symbol.flags & 8192) && + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -23063,10 +23257,8 @@ var ts; } } function createTypeNodeFromObjectType(type) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - return createMappedTypeNodeFromType(type); - } + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -23130,14 +23322,14 @@ var ts; var length_2 = outerTypeParameters.length; while (i < length_2) { var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_7 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_7); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); - var namePart = symbolToTypeReferenceName(parent); + var namePart = symbolToTypeReferenceName(parent_7); (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); @@ -23367,11 +23559,11 @@ var ts; var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + var parentChain = getSymbolChain(parent_8, getQualifiedLeftMeaning(meaning), false); if (parentChain) { - parentSymbol = parent; + parentSymbol = parent_8; accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); } } @@ -23389,9 +23581,9 @@ var ts; function getNameOfSymbol(symbol, context) { var declaration = ts.firstOrUndefined(symbol.declarations); if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - return ts.declarationNameToString(name); + var name_15 = ts.getNameOfDeclaration(declaration); + if (name_15) { + return ts.declarationNameToString(name_15); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -23471,9 +23663,9 @@ var ts; function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - var name = ts.getNameOfDeclaration(declaration); - if (name) { - return ts.declarationNameToString(name); + var name_16 = ts.getNameOfDeclaration(declaration); + if (name_16) { + return ts.declarationNameToString(name_16); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -23536,9 +23728,9 @@ var ts; var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), false); + var parent_9 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_9) { + walkSymbol(parent_9, getQualifiedLeftMeaning(meaning), false); } } if (accessibleSymbolChain) { @@ -23583,9 +23775,9 @@ var ts; writeTypeReference(type, nextFlags); } else if (type.flags & 256 && !(type.flags & 65536)) { - var parent = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); - if (getDeclaredTypeOfSymbol(parent) !== type) { + var parent_10 = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent_10, writer, enclosingDeclaration, 793064, 0, nextFlags); + if (getDeclaredTypeOfSymbol(parent_10) !== type) { writePunctuation(writer, 23); appendSymbolNameOnly(type.symbol, writer); } @@ -23594,7 +23786,7 @@ var ts; buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 1024) && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + ((flags & 65536) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); } @@ -23685,12 +23877,12 @@ var ts; var length_3 = outerTypeParameters.length; while (i < length_3) { var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_11 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_11); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_11, typeArguments, start, i, flags); writePunctuation(writer, 23); } } @@ -23738,9 +23930,7 @@ var ts; if (!symbolStack) { symbolStack = []; } - var isConstructorObject = type.flags & 32768 && - getObjectFlags(type) & 16 && - type.symbol && type.symbol.flags & 32; + var isConstructorObject = type.objectFlags & 16 && type.symbol && type.symbol.flags & 32; if (isConstructorObject) { writeLiteralType(type, flags); } @@ -23755,16 +23945,16 @@ var ts; writeLiteralType(type, flags); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isStaticMethodSymbol = !!(symbol.flags & 8192) && + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { + ts.some(symbol.declarations, function (declaration) { return declaration.parent.kind === 265 || declaration.parent.kind === 234; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 4) || - (ts.contains(symbolStack, symbol)); + ts.contains(symbolStack, symbol); } } } @@ -23801,11 +23991,9 @@ var ts; return false; } function writeLiteralType(type, flags) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - writeMappedType(type); - return; - } + if (isGenericMappedType(type)) { + writeMappedType(type); + return; } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -24161,19 +24349,19 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent = getDeclarationContainer(node); + var parent_12 = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 237 && parent.kind !== 265 && ts.isInAmbientContext(parent))) { - return isGlobalSourceFile(parent); + !(node.kind !== 237 && parent_12.kind !== 265 && ts.isInAmbientContext(parent_12))) { + return isGlobalSourceFile(parent_12); } - return isDeclarationVisible(parent); + return isDeclarationVisible(parent_12); case 149: case 148: case 153: case 154: case 151: case 150: - if (ts.getModifierFlags(node) & (8 | 16)) { + if (ts.hasModifier(node, 8 | 16)) { return false; } case 152: @@ -24328,8 +24516,8 @@ var ts; var members = ts.createSymbolTable(); var names = ts.createUnderscoreEscapedMap(); for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var name = properties_2[_i]; - names.set(ts.getTextOfPropertyName(name), true); + var name_17 = properties_2[_i]; + names.set(ts.getTextOfPropertyName(name_17), true); } for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; @@ -24373,20 +24561,20 @@ var ts; type = getRestType(parentType, literalMembers, declaration.symbol); } else { - var name = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name)) { + var name_18 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_18)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = ts.getTextOfPropertyName(name); + var text = ts.getTextOfPropertyName(name_18); var declaredType = getTypeOfPropertyOfType(parentType, text); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); + error(name_18, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_18)); return unknownType; } } @@ -24532,8 +24720,8 @@ var ts; 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)); + var name_19 = ts.getNameOfDeclaration(declaration); + error(name_19, 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_19), typeToString(jsDocType), typeToString(declarationType)); } } else if (!jsDocType) { @@ -24850,8 +25038,8 @@ var ts; } } function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; @@ -24975,7 +25163,7 @@ var ts; return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + type.resolvedBaseTypes = ts.emptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { return; @@ -25017,12 +25205,7 @@ var ts; error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); return; } - if (type.resolvedBaseTypes === ts.emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } + type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type) { var outerTypeParameters = type.outerTypeParameters; @@ -25120,7 +25303,9 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var declaration = ts.findDeclaration(symbol, function (d) { return d.kind === 283 || d.kind === 231; }); + var declaration = ts.find(symbol.declarations, function (d) { + return d.kind === 283 || d.kind === 231; + }); var type = getTypeFromTypeNode(declaration.kind === 283 ? declaration.typeExpression : declaration.type); if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -25612,17 +25797,12 @@ var ts; } else { var members = emptySymbols; - var constructSignatures = ts.emptyArray; var stringIndexInfo = undefined; if (symbol.exports) { members = getExportsOfSymbol(symbol); } if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); - constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); - if (!constructSignatures.length) { - constructSignatures = getDefaultConstructSignatures(classType); - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (32768 | 131072 | 540672)) { members = ts.createSymbolTable(getNamedMembers(members)); @@ -25633,10 +25813,18 @@ var ts; } } var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; - setStructuredTypeMembers(type, members, ts.emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); if (symbol.flags & (16 | 8192)) { type.callSignatures = getSignaturesOfSymbol(symbol); } + if (symbol.flags & 32) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } } } function resolveMappedTypeMembers(type) { @@ -25719,8 +25907,7 @@ var ts; return getObjectFlags(type) & 32 && !!type.declaration.questionToken; } function isGenericMappedType(type) { - return getObjectFlags(type) & 32 && - maybeTypeOfKind(getConstraintTypeFromMappedType(type), 540672 | 262144); + return getObjectFlags(type) & 32 && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -25820,6 +26007,10 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + var transformed = getTransformedIndexedAccessType(type); + if (transformed) { + return transformed; + } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; @@ -25882,11 +26073,18 @@ var ts; return stringType; } if (t.flags & 524288) { + var transformed = getTransformedIndexedAccessType(t); + if (transformed) { + return getBaseConstraint(transformed); + } var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; } + if (isGenericMappedType(t)) { + return emptyObjectType; + } return t; } } @@ -26353,9 +26551,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - 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)); + var name_20 = ts.getNameOfDeclaration(declaration); + if (name_20) { + error(name_20, 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_20)); } 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); @@ -26366,6 +26564,9 @@ var ts; } return signature.resolvedReturnType; } + function isResolvingReturnTypeOfSignature(signature) { + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3) >= 0; + } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); @@ -26434,7 +26635,7 @@ var ts; function getIndexInfoOfSymbol(symbol, kind) { var declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64), declaration); } return undefined; } @@ -26702,8 +26903,8 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; switch (declaration.kind) { case 229: case 230: @@ -27160,17 +27361,16 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { + if (!(indexType.flags & 6144) && isTypeAssignableToKind(indexType, 262178 | 84 | 512)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || + var indexInfo = isTypeAssignableToKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || getIndexInfoOfType(objectType, 0) || undefined; if (indexInfo) { if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); - return unknownType; } return indexInfo.type; } @@ -27202,25 +27402,68 @@ var ts; return anyType; } function getIndexedAccessForMappedType(type, indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - return unknownType; + if (accessNode) { + if (!isTypeAssignableTo(indexType, getIndexType(type))) { + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(type)); + return unknownType; + } + if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && type.declaration.readonlyToken) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + } } var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); } + function isGenericObjectType(type) { + return type.flags & 540672 ? true : + getObjectFlags(type) & 32 ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : + type.flags & 196608 ? ts.forEach(type.types, isGenericObjectType) : + false; + } + function isGenericIndexType(type) { + return type.flags & (540672 | 262144) ? true : + type.flags & 196608 ? ts.forEach(type.types, isGenericIndexType) : + false; + } + function isStringIndexOnlyType(type) { + if (type.flags & 32768 && !isGenericMappedType(type)) { + var t = resolveStructuredTypeMembers(type); + return t.properties.length === 0 && + t.callSignatures.length === 0 && t.constructSignatures.length === 0 && + t.stringIndexInfo && !t.numberIndexInfo; + } + return false; + } + function getTransformedIndexedAccessType(type) { + var objectType = type.objectType; + if (objectType.flags & 131072 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0)); + } + else { + regularTypes.push(t); + } + } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + return undefined; + } function getIndexedAccessType(objectType, indexType, accessNode) { - if (maybeTypeOfKind(indexType, 540672 | 262144) || - maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 180) || - isGenericMappedType(objectType)) { + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { return objectType; } - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } var id = objectType.id + "," + indexType.id; var type = indexedAccessTypes.get(id); if (!type) { @@ -27419,7 +27662,7 @@ var ts; var container = ts.getThisContainer(node, false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { - if (!(ts.getModifierFlags(container) & 32) && + if (!ts.hasModifier(container, 32) && (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } @@ -27566,7 +27809,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.signature, mapper.flags | 2, mapper.inferences) : + createInferenceContext(mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : mapper; } function identityMapper(type) { @@ -27830,11 +28073,13 @@ var ts; if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind === 187) { - return false; + if (node.kind !== 187) { + var parameter = ts.firstOrUndefined(node.parameters); + if (!(parameter && ts.parameterIsThisKeyword(parameter))) { + return true; + } } - var parameter = ts.firstOrUndefined(node.parameters); - return !(parameter && ts.parameterIsThisKeyword(parameter)); + return node.body.kind === 207 ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); @@ -27897,7 +28142,7 @@ var ts; return 0; } if (source.typeParameters) { - source = instantiateSignatureInContextOf(source, target); + source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var result = -1; var sourceThisType = getThisTypeOfSignature(source); @@ -27946,7 +28191,7 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(source); if (target.typePredicate) { if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(target.typePredicate)) { if (reportErrors) { @@ -27962,7 +28207,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -27971,11 +28216,13 @@ var ts; return 0; } if (source.kind === 1) { - var sourceIdentifierPredicate = source; - var targetIdentifierPredicate = target; - if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + var sourcePredicate = source; + var targetPredicate = target; + var sourceIndex = sourcePredicate.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); + var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); + if (sourceIndex !== targetIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourcePredicate.parameterName, targetPredicate.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0; @@ -28120,8 +28367,7 @@ var ts; return true; } if (source.flags & 32768 && target.flags & 32768) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); + var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1; } @@ -28234,11 +28480,21 @@ var ts; !(target.flags & 65536) && !isIntersectionConstituent && source !== globalObjectType && - getPropertiesOfType(source).length > 0 && + (getPropertiesOfType(source).length > 0 || + getSignaturesOfType(source, 0).length > 0 || + getSignaturesOfType(source, 1).length > 0) && isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { - reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + var calls = getSignaturesOfType(source, 0); + var constructs = getSignaturesOfType(source, 1); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } } return 0; } @@ -28439,7 +28695,7 @@ var ts; if (overflow) { return 0; } - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var id = getRelationKey(source, target, relation); var related = relation.get(id); if (related !== undefined) { if (reportErrors && related === 2) { @@ -28859,6 +29115,9 @@ var ts; if (sourceInfo) { return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); } + if (isGenericMappedType(source)) { + return kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + } if (isObjectLiteralType(source)) { var related = -1; if (kind === 0) { @@ -28892,8 +29151,8 @@ var ts; if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; - var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24); if (targetAccessibility === 8) { return true; } @@ -28909,6 +29168,42 @@ var ts; return false; } } + function isUnconstrainedTypeParameter(type) { + return type.flags & 16384 && !getConstraintFromTypeParameter(type); + } + function isTypeReferenceWithGenericArguments(type) { + return getObjectFlags(type) & 4 && ts.some(type.typeArguments, isUnconstrainedTypeParameter); + } + function getTypeReferenceId(type, typeParameters) { + var result = "" + type.target.id; + for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { + var t = _a[_i]; + if (isUnconstrainedTypeParameter(t)) { + var index = ts.indexOf(typeParameters, t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + } + else { + result += "-" + t.id; + } + } + return result; + } + function getRelationKey(source, target, relation) { + if (relation === identityRelation && source.id > target.id) { + var temp = source; + source = target; + target = temp; + } + if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { + var typeParameters = []; + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + } + return source.id + "," + target.id; + } function forEachProperty(prop, callback) { if (ts.getCheckFlags(prop) & 6) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { @@ -28945,7 +29240,7 @@ var ts; var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.getModifierFlags(declaration) & 128) { + if (declaration && ts.hasModifier(declaration, 128)) { return true; } } @@ -29331,13 +29626,14 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(signature, flags, baseInferences) { + function createInferenceContext(signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); var context = mapper; context.mappedTypes = signature.typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; + context.compareTypes = compareTypes || compareTypesAssignable; return context; function mapper(t) { for (var i = 0; i < inferences.length; i++) { @@ -29425,6 +29721,19 @@ var ts; return inference.candidates && getUnionType(inference.candidates, true); } } + function isPossiblyAssignableTo(source, target) { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + if (!(targetProp.flags & (16777216 | 4194304))) { + var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (!sourceProp) { + return false; + } + } + } + return true; + } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; @@ -29585,15 +29894,17 @@ var ts; return; } } - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target); + if (isPossiblyAssignableTo(source, target) || isPossiblyAssignableTo(target, source)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target); + } } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { - var targetProp = properties_5[_i]; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -29692,7 +30003,7 @@ var ts; var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { inference.inferredType = inferredType = instantiatedConstraint; } } @@ -29740,27 +30051,17 @@ var ts; } return undefined; } - function getLeftmostIdentifierOrThis(node) { - switch (node.kind) { - case 71: - case 99: - return node; - case 179: - return getLeftmostIdentifierOrThis(node.expression); - } - return undefined; - } function getBindingElementNameText(element) { if (element.parent.kind === 174) { - var name = element.propertyName || element.name; - switch (name.kind) { + var name_21 = element.propertyName || element.name; + switch (name_21.kind) { case 71: - return ts.unescapeLeadingUnderscores(name.escapedText); + return ts.unescapeLeadingUnderscores(name_21.escapedText); case 144: - return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + return ts.isStringOrNumericLiteral(name_21.expression) ? name_21.expression.text : undefined; case 9: case 8: - return name.text; + return name_21.text; default: ts.Debug.fail("Unexpected name kind for binding element name"); } @@ -30241,7 +30542,7 @@ var ts; parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 84); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -30387,7 +30688,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { + if (isTypeAssignableToKind(indexType, 84)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -31073,7 +31374,7 @@ var ts; break; case 149: case 148: - if (ts.getModifierFlags(container) & 32) { + if (ts.hasModifier(container, 32)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -31164,14 +31465,14 @@ var ts; if (!isCallExpression && container.kind === 152) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } - if ((ts.getModifierFlags(container) & 32) || isCallExpression) { + if (ts.hasModifier(container, 32) || isCallExpression) { nodeCheckFlag = 512; } else { nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 151 && ts.getModifierFlags(container) & 256) { + if (container.kind === 151 && ts.hasModifier(container, 256)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } @@ -31216,7 +31517,7 @@ var ts; } else { if (ts.isClassLike(container.parent) || container.parent.kind === 178) { - if (ts.getModifierFlags(container) & 32) { + if (ts.hasModifier(container, 32)) { return container.kind === 151 || container.kind === 150 || container.kind === 153 || @@ -31349,11 +31650,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; + var name_22 = declaration.propertyName || declaration.name; if (parentDeclaration.kind !== 176) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); - if (parentTypeNode && !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); + if (parentTypeNode && !ts.isBindingPattern(name_22)) { + var text = ts.getTextOfPropertyName(name_22); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); } @@ -31406,7 +31707,7 @@ var ts; return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); - if (signature) { + if (signature && !isResolvingReturnTypeOfSignature(signature)) { return getReturnTypeOfSignature(signature); } return undefined; @@ -31510,11 +31811,11 @@ var ts; return undefined; } if (ts.isJsxAttribute(node.parent)) { - return getTypeOfPropertyOfType(attributesType, node.parent.name.escapedText); + return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); } else if (node.parent.kind === 249) { var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; + return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; } else { return attributesType; @@ -31526,7 +31827,7 @@ var ts; if (!attributesType || isTypeAny(attributesType)) { return undefined; } - return getTypeOfPropertyOfType(attributesType, attribute.name.escapedText); + return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { return attributesType; @@ -31742,10 +32043,7 @@ var ts; } } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); - } - function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || isTypeOfKind(type, kind); + return isTypeAssignableToKind(checkComputedPropertyName(name), 84); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -31757,7 +32055,9 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 84 | 262178 | 512)) { + if (links.resolvedType.flags & 6144 || + !isTypeAssignableToKind(links.resolvedType, 262178 | 84 | 512) && + !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -32242,9 +32542,7 @@ var ts; return undefined; } function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (!elementType) { - elementType = checkExpression(openingLikeElement.tagName); - } + if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } if (elementType.flags & 65536) { var types = elementType.types; return getUnionType(types.map(function (type) { @@ -32339,11 +32637,12 @@ var ts; } function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { + var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; + if (!links[linkLocation]) { var elemClassType = getJsxGlobalElementClassType(); - return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); } - return links.resolvedJsxElementAttributesType; + return links[linkLocation]; } function getAllAttributesTypeFromJsxOpeningLikeElement(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -32570,9 +32869,12 @@ var ts; } var prop = getPropertyOfType(apparentType, right.escapedText); if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0); - if (stringIndexType) { - return stringIndexType; + var indexInfo = getIndexInfoOfType(apparentType, 0); + if (indexInfo && indexInfo.type) { + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + return indexInfo.type; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); @@ -32699,7 +33001,7 @@ var ts; if (prop && noUnusedIdentifiers && (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8)) { if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } @@ -32867,19 +33169,19 @@ var ts; 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; + var parent_13 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent === lastParent) { + if (lastParent && parent_13 === lastParent) { index++; } else { - lastParent = parent; + lastParent = parent_13; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent; + lastParent = parent_13; } lastSymbol = symbol; if (signature.hasLiteralTypes) { @@ -32970,8 +33272,8 @@ var ts; } return undefined; } - function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature, 1); + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + var context = createInferenceContext(signature, 1, compareTypes); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); @@ -33201,7 +33503,7 @@ var ts; return getLiteralType(element.name.text); case 144: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512)) { + if (isTypeAssignableToKind(nameType, 512)) { return nameType; } else { @@ -33294,9 +33596,10 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); + var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; var excludeArgument; var excludeCount = 0; - if (!isDecorator) { + if (!isDecorator && !isSingleNonGenericCandidate) { for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { if (isContextSensitive(args[i])) { if (!excludeArgument) { @@ -33388,6 +33691,17 @@ var ts; if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; candidateForTypeArgumentError = undefined; + if (isSingleNonGenericCandidate) { + var candidate = candidates[0]; + if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + return undefined; + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + candidateForArgumentError = candidate; + return undefined; + } + return candidate; + } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { @@ -33518,7 +33832,7 @@ var ts; return resolveErrorCall(node); } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { + if (valueDecl && ts.hasModifier(valueDecl, 128)) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } @@ -33554,8 +33868,8 @@ var ts; return true; } var declaration = signature.declaration; - var modifiers = ts.getModifierFlags(declaration); - if (!(modifiers & 24)) { + var modifiers = ts.getSelectedModifierFlags(declaration, 24); + if (!modifiers) { return true; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -33709,7 +34023,7 @@ var ts; && getSymbolLinks(type.symbol).inferredClassType === type; } function checkCallExpression(node) { - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); + checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 97) { return voidType; @@ -33742,7 +34056,7 @@ var ts; return getReturnTypeOfSignature(signature); } function checkImportCallExpression(node) { - checkGrammarArguments(node, node.arguments) || checkGrammarImportCallExpression(node); + checkGrammarArguments(node.arguments) || checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } @@ -33758,11 +34072,33 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeOfSymbol(esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); } } return createPromiseReturnType(node, anyType); } + function getTypeWithSyntheticDefaultImportType(type, symbol) { + if (allowSyntheticDefaultImports && type && type !== unknownType) { + var synthType = type; + if (!synthType.syntheticType) { + if (!getPropertyOfType(type, "default")) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152, "default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default", newSymbol); + var anonymousSymbol = createSymbol(2048, "__type"); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined); + anonymousSymbol.type = defaultContainingObject; + synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + } + else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } function isCommonJsRequire(node) { if (!ts.isRequireCall(node, true)) { return false; @@ -33881,15 +34217,15 @@ var ts; } } } - function assignBindingElementTypes(node) { - if (ts.isBindingPattern(node.name)) { - for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); - } - assignBindingElementTypes(element); + function assignBindingElementTypes(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 71) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + else { + assignBindingElementTypes(element.name); } } } @@ -33898,12 +34234,13 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = contextualType; - var name = ts.getNameOfDeclaration(parameter.valueDeclaration); - if (links.type === emptyObjectType && - (name.kind === 174 || name.kind === 175)) { - links.type = getTypeFromBindingPattern(name); + var decl = parameter.valueDeclaration; + if (decl.name.kind !== 71) { + if (links.type === emptyObjectType) { + links.type = getTypeFromBindingPattern(decl.name); + } + assignBindingElementTypes(decl.name); } - assignBindingElementTypes(parameter.valueDeclaration); } } function createPromiseType(promisedType) { @@ -34104,14 +34441,14 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186) { - checkGrammarForGenerator(node); - } if (checkMode === 1 && isContextSensitive(node)) { checkNodeDeferred(node); return anyFunctionType; } + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 186) { + checkGrammarForGenerator(node); + } var links = getNodeLinks(node); var type = getTypeOfSymbol(node.symbol); if (!(links.flags & 1024)) { @@ -34181,7 +34518,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { + if (!isTypeAssignableToKind(type, 84)) { error(operand, diagnostic); return false; } @@ -34269,8 +34606,13 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + if (node.operand.kind === 8) { + if (node.operator === 38) { + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + } + else if (node.operator === 37) { + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } } switch (node.operator) { case 37: @@ -34322,30 +34664,22 @@ var ts; } return false; } - function isTypeOfKind(type, kind) { - if (type.flags & kind) { + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { return true; } - if (type.flags & 65536) { - var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; - if (!isTypeOfKind(t, kind)) { - return false; - } - } - return true; + if (strict && source.flags & (1 | 1024 | 2048 | 4096)) { + return false; } - if (type.flags & 131072) { - var types = type.types; - for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { - var t = types_19[_a]; - if (isTypeOfKind(t, kind)) { - return true; - } - } - } - return false; + return (kind & 84 && isTypeAssignableTo(source, numberType)) || + (kind & 262178 && isTypeAssignableTo(source, stringType)) || + (kind & 136 && isTypeAssignableTo(source, booleanType)) || + (kind & 1024 && isTypeAssignableTo(source, voidType)) || + (kind & 8192 && isTypeAssignableTo(source, neverType)) || + (kind & 4096 && isTypeAssignableTo(source, nullType)) || + (kind & 2048 && isTypeAssignableTo(source, undefinedType)) || + (kind & 512 && isTypeAssignableTo(source, esSymbolType)) || + (kind & 16777216 && isTypeAssignableTo(source, nonPrimitiveType)); } function isConstEnumObjectType(type) { return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); @@ -34357,7 +34691,7 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (isTypeOfKind(leftType, 8190)) { + if (!isTypeAny(leftType) && isTypeAssignableToKind(leftType, 8190)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(isTypeAny(rightType) || @@ -34374,32 +34708,32 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 84 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(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)) { + if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var p = properties_6[_i]; + for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { + var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); } return sourceType; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { if (property.kind === 261 || property.kind === 262) { - var name = property.name; - if (name.kind === 144) { - checkComputedPropertyName(name); + var name_23 = property.name; + if (name_23.kind === 144) { + checkComputedPropertyName(name_23); } - if (isComputedNonLiteralName(name)) { + if (isComputedNonLiteralName(name_23)) { return undefined; } - var text = ts.getTextOfPropertyName(name); + var text = ts.getTextOfPropertyName(name_23); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -34414,7 +34748,7 @@ var ts; } } else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + error(name_23, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_23)); } } else if (property.kind === 263) { @@ -34641,24 +34975,22 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeOfKind(leftType, 1 | 262178) && !isTypeOfKind(rightType, 1 | 262178)) { + if (!isTypeAssignableToKind(leftType, 262178) && !isTypeAssignableToKind(rightType, 262178)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { + if (isTypeAssignableToKind(leftType, 84, true) && isTypeAssignableToKind(rightType, 84, true)) { resultType = numberType; } - else { - if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { - resultType = stringType; - } - else if (isTypeAny(leftType) || isTypeAny(rightType)) { - resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; - } - if (resultType && !checkForDisallowedESSymbolOperand(operator)) { - return resultType; - } + else if (isTypeAssignableToKind(leftType, 262178, true) || isTypeAssignableToKind(rightType, 262178, true)) { + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; + } + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; } if (!resultType) { reportOperatorError(); @@ -34823,13 +35155,12 @@ var ts; return getBestChoiceType(type1, type2); } function checkLiteralExpression(node) { - if (node.kind === 8) { - checkGrammarNumericLiteral(node); - } switch (node.kind) { + case 13: case 9: return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: + checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: return trueType; @@ -34977,6 +35308,7 @@ var ts; return checkSuperExpression(node); case 95: return nullWideningType; + case 13: case 9: case 8: case 101: @@ -34984,8 +35316,6 @@ var ts; return checkLiteralExpression(node); case 196: return checkTemplateExpression(node); - case 13: - return stringType; case 12: return globalRegExpType; case 177: @@ -35076,7 +35406,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.getModifierFlags(node) & 92) { + if (ts.hasModifier(node, 92)) { func = ts.getContainingFunction(node); if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -35136,9 +35466,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name = _a[_i].name; - if (ts.isBindingPattern(name) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + var name_24 = _a[_i].name; + if (ts.isBindingPattern(name_24) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_24, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -35158,9 +35488,9 @@ var ts; case 160: case 151: case 150: - var parent = node.parent; - if (node === parent.type) { - return parent; + var parent_14 = node.parent; + if (node === parent_14.type) { + return parent_14; } } } @@ -35170,13 +35500,13 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name = element.name; - if (name.kind === 71 && name.escapedText === predicateVariableName) { + var name_25 = element.name; + if (name_25.kind === 71 && name_25.escapedText === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 175 || name.kind === 174) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + else if (name_25.kind === 175 || name_25.kind === 174) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_25, predicateVariableNode, predicateVariableName)) { return true; } } @@ -35266,7 +35596,7 @@ var ts; } } else { - var isStatic = ts.getModifierFlags(member) & 32; + var isStatic = ts.hasModifier(member, 32); var names = isStatic ? staticNames : instanceNames; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { @@ -35311,7 +35641,7 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; var memberNameNode = member.name; - var isStatic = ts.getModifierFlags(member) & 32; + var isStatic = ts.hasModifier(member, 32); if (isStatic && memberNameNode) { var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); switch (memberName) { @@ -35399,7 +35729,7 @@ var ts; function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); checkFunctionOrMethodDeclaration(node); - if (ts.getModifierFlags(node) & 128 && node.body) { + if (ts.hasModifier(node, 128) && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -35435,17 +35765,9 @@ var ts; } return ts.forEachChild(n, containsSuperCall); } - function markThisReferencesAsErrors(n) { - if (n.kind === 99) { - error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - } - else if (n.kind !== 186 && n.kind !== 228) { - ts.forEachChild(n, markThisReferencesAsErrors); - } - } function isInstancePropertyWithInitializer(n) { return n.kind === 149 && - !(ts.getModifierFlags(n) & 32) && + !ts.hasModifier(n, 32) && !!n.initializer; } var containingClassDecl = node.parent; @@ -35457,8 +35779,8 @@ var ts; if (classExtendsNull) { error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); + var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92); }); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; @@ -35501,10 +35823,12 @@ var ts; var otherKind = node.kind === 153 ? 154 : 153; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { + var nodeFlags = ts.getModifierFlags(node); + var otherFlags = ts.getModifierFlags(otherAccessor); + if ((nodeFlags & 28) !== (otherFlags & 28)) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { + if ((nodeFlags & 128) !== (otherFlags & 128)) { error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); @@ -35550,7 +35874,7 @@ var ts; function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); if (node.kind === 159 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { - grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); if (type !== unknownType) { @@ -35558,7 +35882,14 @@ var ts; ts.forEach(node.typeArguments, checkSourceElement); if (produceDiagnostics) { var symbol = getNodeLinks(node).resolvedSymbol; - var typeParameters = symbol.flags & 524288 ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; + if (!symbol) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return; + } + var typeParameters = symbol.flags & 524288 && getSymbolLinks(symbol).typeParameters; + if (!typeParameters && getObjectFlags(type) & 4) { + typeParameters = type.target.localTypeParameters; + } checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } @@ -35601,16 +35932,15 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { - var constraint = getBaseConstraintOfType(objectType); - if (constraint && getIndexInfoOfType(constraint, 1)) { - return type; - } + if (getIndexInfoOfType(getApparentType(objectType), 1) && isTypeAssignableToKind(indexType, 84)) { + return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); return type; } function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } function checkMappedType(node) { @@ -35621,7 +35951,7 @@ var ts; checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); } function isPrivateWithinAmbient(node) { - return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); + return ts.hasModifier(node, 8) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); @@ -35708,9 +36038,9 @@ var ts; (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { var reportError = (node.kind === 151 || node.kind === 150) && - (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); + ts.hasModifier(node, 32) !== ts.hasModifier(subsequentNode, 32); if (reportError) { - var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + var diagnostic = ts.hasModifier(node, 32) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -35726,7 +36056,7 @@ var ts; error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); } else { - if (ts.getModifierFlags(node) & 128) { + if (ts.hasModifier(node, 128)) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -35736,8 +36066,8 @@ var ts; } var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var current = declarations_5[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; @@ -35786,7 +36116,7 @@ var ts; }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -35845,12 +36175,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); + var name_26 = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - 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)); + error(name_26, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name_26)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + error(name_26, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name_26)); } } } @@ -36195,7 +36525,7 @@ var ts; if (!ts.hasDynamicName(node)) { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)); }); + var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536); }); if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); } @@ -36285,12 +36615,12 @@ 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); + var name_27 = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(name)) { - error(name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); + !parameterNameStartsWithUnderscore(name_27)) { + error(name_27, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); } } else if (compilerOptions.noUnusedLocals) { @@ -36330,14 +36660,14 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 151 || member.kind === 149) { - if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { + if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); } } else if (member.kind === 152) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); } } @@ -36526,8 +36856,8 @@ var ts; container.kind === 233 || container.kind === 265); if (!namesShareScope) { - var name = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + var name_28 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_28, name_28); } } } @@ -36604,13 +36934,13 @@ var ts; if (node.propertyName && node.propertyName.kind === 144) { checkComputedPropertyName(node.propertyName); } - var parent = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent); - var name = node.propertyName || node.name; - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + var parent_15 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_15); + var name_29 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name_29)); markPropertyAsReferenced(property); - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); + if (parent_15.initializer && property) { + checkPropertyAccessibility(parent_15, parent_15.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -36677,7 +37007,7 @@ var ts; 128 | 64 | 32; - return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); + return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); @@ -36807,7 +37137,7 @@ var ts; checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { + if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -37179,7 +37509,7 @@ var ts; var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { + if (!ts.hasModifier(member, 32) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); @@ -37275,10 +37605,10 @@ var ts; } var type = getDeclaredTypeOfSymbol(symbol); if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { - var name = symbolToString(symbol); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; - error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + var name_30 = symbolToString(symbol); + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name_30); } } } @@ -37286,8 +37616,8 @@ var ts; function areTypeParametersIdentical(declarations, typeParameters) { var maxTypeArgumentCount = ts.length(typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; var numTypeParameters = ts.length(declaration.typeParameters); if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { return false; @@ -37323,7 +37653,7 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (!node.name && !(ts.getModifierFlags(node) & 512)) { + if (!node.name && !ts.hasModifier(node, 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -37416,7 +37746,7 @@ var ts; var signatures = getSignaturesOfType(type, 1); if (signatures.length) { var declaration = signatures[0].declaration; - if (declaration && ts.getModifierFlags(declaration) & 8) { + if (declaration && ts.hasModifier(declaration, 8)) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); @@ -37449,7 +37779,7 @@ var ts; if (derived) { if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128))) { if (derivedClassDecl.kind === 199) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -37497,8 +37827,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { - var prop = properties_7[_a]; + for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { + var prop = properties_8[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -37666,16 +37996,16 @@ var ts; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384) { - var name = void 0; + var name_31; if (ex.kind === 179) { - name = ex.name.escapedText; + name_31 = ex.name.escapedText; } else { var argument = ex.argumentExpression; ts.Debug.assert(ts.isLiteralExpression(argument)); - name = ts.escapeLeadingUnderscores(argument.text); + name_31 = ts.escapeLeadingUnderscores(argument.text); } - return evaluateEnumMember(expr, type.symbol, name); + return evaluateEnumMember(expr, type.symbol, name_31); } } break; @@ -37752,8 +38082,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; if ((declaration.kind === 229 || (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { @@ -37873,9 +38203,9 @@ var ts; break; case 176: case 226: - var name = node.name; - if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var name_32 = node.name; + if (ts.isBindingPattern(name_32)) { + for (var _b = 0, _c = name_32.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -37968,7 +38298,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -37995,7 +38325,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (ts.getModifierFlags(node) & 1) { + if (ts.hasModifier(node, 1)) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -38023,7 +38353,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -38081,7 +38411,7 @@ var ts; } return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 71) { @@ -38128,8 +38458,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -38407,7 +38737,7 @@ var ts; return []; } var symbols = ts.createSymbolTable(); - var memberFlags = 0; + var isStatic = false; populateSymbols(); return symbolsToArray(symbols); function populateSymbols() { @@ -38429,7 +38759,7 @@ var ts; } case 229: case 230: - if (!(memberFlags & 32)) { + if (!isStatic) { copySymbols(getSymbolOfNode(location).members, meaning & 793064); } break; @@ -38443,7 +38773,7 @@ var ts; if (ts.introducesArgumentsExoticObject(location)) { copySymbol(argumentsSymbol, meaning); } - memberFlags = ts.getModifierFlags(location); + isStatic = ts.hasModifier(location, 32); location = location.parent; } copySymbols(globals, meaning); @@ -38678,12 +39008,7 @@ var ts; case 8: if (node.parent.kind === 180 && node.parent.argumentExpression === node) { var objectType = getTypeOfExpression(node.parent.expression); - if (objectType === unknownType) - return undefined; - var apparentType = getApparentType(objectType); - if (apparentType === unknownType) - return undefined; - return getPropertyOfType(apparentType, node.text); + return getPropertyOfType(objectType, node.text); } break; } @@ -38779,7 +39104,7 @@ var ts; } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return ts.getModifierFlags(node) & 32 + return ts.hasModifier(node, 32) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -38798,9 +39123,9 @@ var ts; function getRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6) { var symbols_4 = []; - var name_2 = symbol.escapedName; + var name_33 = symbol.escapedName; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_2); + var symbol = getPropertyOfType(t, name_33); if (symbol) { symbols_4.push(symbol); } @@ -39004,13 +39329,13 @@ var ts; return strictNullChecks && !isOptionalParameter(parameter) && parameter.initializer && - !(ts.getModifierFlags(parameter) & 92); + !ts.hasModifier(parameter, 92); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - !!(ts.getModifierFlags(parameter) & 92); + ts.hasModifier(parameter, 92); } function getNodeCheckFlags(node) { return getNodeLinks(node).flags; @@ -39066,22 +39391,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { + else if (isTypeAssignableToKind(type, 1024 | 6144 | 8192)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeOfKind(type, 136)) { + else if (isTypeAssignableToKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 84)) { + else if (isTypeAssignableToKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 262178)) { + else if (isTypeAssignableToKind(type, 262178)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 512)) { + else if (isTypeAssignableToKind(type, 512)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -39122,9 +39447,9 @@ var ts; } var location = reference; if (startInDeclarationContainer) { - var parent = reference.parent; - if (ts.isDeclaration(parent) && reference === parent.name) { - location = getDeclarationContainer(parent); + var parent_16 = reference.parent; + if (ts.isDeclaration(parent_16) && reference === parent_16.name) { + location = getDeclarationContainer(parent_16); } } return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined); @@ -39249,9 +39574,9 @@ var ts; } var current = symbol; while (true) { - var parent = getParentOfSymbol(current); - if (parent) { - current = parent; + var parent_17 = getParentOfSymbol(current); + if (parent_17) { + current = parent_17; } else { break; @@ -39339,10 +39664,10 @@ var ts; var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; for (var helper = 1; helper <= 32768; helper <<= 1) { if (uncheckedHelpers & helper) { - var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455); + var name_34 = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name_34), 107455); if (!symbol) { - error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name_34); } } } @@ -39546,7 +39871,7 @@ var ts; node.kind !== 154) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 229 && ts.getModifierFlags(node.parent) & 128)) { + if (!(node.parent.kind === 229 && ts.hasModifier(node.parent, 128))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -39665,8 +39990,7 @@ var ts; if (list && list.hasTrailingComma) { var start = list.end - ",".length; var end = list.end; - var sourceFile = ts.getSourceFileOfNode(list[0]); - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + return grammarErrorAtPos(list[0], start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); } } function checkGrammarTypeParameterList(typeParameters, file) { @@ -39742,7 +40066,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (ts.getModifierFlags(parameter) !== 0) { + if (ts.hasModifiers(parameter)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -39776,19 +40100,18 @@ var ts; return checkGrammarForDisallowedTrailingComma(typeArguments) || checkGrammarForAtLeastOneTypeArgument(node, typeArguments); } - function checkGrammarForOmittedArgument(node, args) { + function checkGrammarForOmittedArgument(args) { if (args) { - var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; if (arg.kind === 200) { - return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } } } - function checkGrammarArguments(node, args) { - return checkGrammarForOmittedArgument(node, args); + function checkGrammarArguments(args) { + return checkGrammarForOmittedArgument(args); } function checkGrammarHeritageClause(node) { var types = node.types; @@ -39797,8 +40120,7 @@ var ts; } if (types && types.length === 0) { var listType = ts.tokenToString(node.token); - var sourceFile = ts.getSourceFileOfNode(node); - return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } return ts.forEach(types, checkGrammarExpressionWithTypeArguments); } @@ -39892,9 +40214,9 @@ var ts; if (prop.kind === 263) { continue; } - var name = prop.name; - if (name.kind === 144) { - checkGrammarComputedPropertyName(name); + var name_35 = prop.name; + if (name_35.kind === 144) { + checkGrammarComputedPropertyName(name_35); } if (prop.kind === 262 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); @@ -39910,8 +40232,8 @@ var ts; var currentKind = void 0; if (prop.kind === 261 || prop.kind === 262) { checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name.kind === 8) { - checkGrammarNumericLiteral(name); + if (name_35.kind === 8) { + checkGrammarNumericLiteral(name_35); } currentKind = Property; } @@ -39927,7 +40249,7 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_35); if (effectiveName === undefined) { continue; } @@ -39937,18 +40259,18 @@ var ts; } else { if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + grammarErrorOnNode(name_35, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_35)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen.set(effectiveName, currentKind | existingKind); } else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_35, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_35, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -39961,12 +40283,12 @@ var ts; continue; } var jsxAttr = attr; - var name = jsxAttr.name; - if (!seen.get(name.escapedText)) { - seen.set(name.escapedText, true); + var name_36 = jsxAttr.name; + if (!seen.get(name_36.escapedText)) { + seen.set(name_36.escapedText, true); } else { - return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_36, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 256 && !initializer.expression) { @@ -40021,10 +40343,10 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { - return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } - else if (accessor.body && ts.getModifierFlags(accessor) & 128) { + else if (accessor.body && ts.hasModifier(accessor, 128)) { return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); } else if (accessor.typeParameters) { @@ -40077,7 +40399,7 @@ var ts; return true; } else if (node.body === undefined) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } if (ts.isClassLike(node.parent)) { @@ -40148,7 +40470,7 @@ var ts; return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } } } @@ -40168,12 +40490,12 @@ var ts; } else { var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } else if (!node.initializer) { @@ -40230,7 +40552,7 @@ var ts; return true; } if (!declarationList.declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } } function allowLetAndConstDeclarations(parent) { @@ -40276,7 +40598,8 @@ var ts; return true; } } - function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { + function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); if (!hasParseDiagnostics(sourceFile)) { diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; @@ -40291,7 +40614,7 @@ var ts; } function checkGrammarConstructorTypeParameters(node) { if (node.typeParameters) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + return grammarErrorAtPos(node, node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -40333,7 +40656,7 @@ var ts; node.kind === 244 || node.kind === 243 || node.kind === 236 || - ts.getModifierFlags(node) & (2 | 1 | 512)) { + ts.hasModifier(node, 2 | 1 | 512)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -43102,27 +43425,27 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_8 = []; + var properties_9 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_8.push(getter); + properties_9.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_8.push(setter); + properties_9.push(setter); } - properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_8, multiLine) + ts.createObjectLiteral(properties_9, multiLine) ]), firstAccessor); return ts.aggregateTransformFlags(expression); } @@ -43168,15 +43491,15 @@ var ts; function getName(node, allowComments, allowSourceMaps, emitFlags) { var nodeName = ts.getNameOfDeclaration(node); if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { - var name = ts.getMutableClone(nodeName); + var name_37 = ts.getMutableClone(nodeName); emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) emitFlags |= 1536; if (emitFlags) - ts.setEmitFlags(name, emitFlags); - return name; + ts.setEmitFlags(name_37, emitFlags); + return name_37; } return ts.getGeneratedNameForNode(node); } @@ -43643,8 +43966,8 @@ var ts; function getLocalNameForExternalImport(node, sourceFile) { var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (namespaceDeclaration && !ts.isDefaultImport(node)) { - var name = namespaceDeclaration.name; - return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + var name_38 = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name_38) ? name_38 : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); } if (node.kind === 238 && node.importClause) { return ts.getGeneratedNameForNode(node); @@ -44765,10 +45088,10 @@ var ts; for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { var specifier = _c[_b]; if (!uniqueExports.get(ts.unescapeLeadingUnderscores(specifier.name.escapedText))) { - var name = specifier.propertyName || specifier.name; - exportSpecifiers.add(ts.unescapeLeadingUnderscores(name.escapedText), specifier); - var decl = resolver.getReferencedImportDeclaration(name) - || resolver.getReferencedValueDeclaration(name); + var name_39 = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.unescapeLeadingUnderscores(name_39.escapedText), specifier); + var decl = resolver.getReferencedImportDeclaration(name_39) + || resolver.getReferencedValueDeclaration(name_39); if (decl) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } @@ -44800,11 +45123,11 @@ var ts; } } else { - var name = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { - multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); - exportedNames = ts.append(exportedNames, name); + var name_40 = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name_40.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name_40); + uniqueExports.set(ts.unescapeLeadingUnderscores(name_40.escapedText), true); + exportedNames = ts.append(exportedNames, name_40); } } } @@ -44818,11 +45141,11 @@ var ts; } } else { - var name = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { - multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); - exportedNames = ts.append(exportedNames, name); + var name_41 = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name_41.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name_41); + uniqueExports.set(ts.unescapeLeadingUnderscores(name_41.escapedText), true); + exportedNames = ts.append(exportedNames, name_41); } } } @@ -44965,11 +45288,11 @@ var ts; } } for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { - var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original; - var variable = ts.createVariableDeclaration(name, undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name_42 = _a.name, value = _a.value, location_2 = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name_42, undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); variable.original = original; - ts.setTextRange(variable, location); - if (ts.isIdentifier(name)) { + ts.setTextRange(variable, location_2); + if (ts.isIdentifier(name_42)) { ts.setEmitFlags(variable, 64); } ts.aggregateTransformFlags(variable); @@ -45062,7 +45385,8 @@ var ts; ? undefined : numElements, location), false, location); } - else if (numElements !== 1 && (flattenContext.level < 1 || numElements === 0)) { + else if (numElements !== 1 && (flattenContext.level < 1 || numElements === 0) + || ts.every(elements, ts.isOmittedExpression)) { var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); } @@ -45120,8 +45444,8 @@ var ts; return ts.createElementAccess(value, argumentExpression); } else { - var name = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); - return ts.createPropertyAccess(value, name); + var name_43 = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); + return ts.createPropertyAccess(value, name_43); } } function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { @@ -45269,7 +45593,12 @@ var ts; if (ts.hasModifier(node, 2)) { break; } - recordEmittedDeclarationInScope(node); + if (node.name) { + recordEmittedDeclarationInScope(node); + } + else { + ts.Debug.assert(node.kind === 229 || ts.hasModifier(node, 512)); + } break; } } @@ -45683,8 +46012,8 @@ var ts; && member.initializer !== undefined; } function addInitializedPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { - var property = properties_9[_i]; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; var statement = ts.createStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); @@ -45693,8 +46022,8 @@ var ts; } function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { - var property = properties_10[_i]; + for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { + var property = properties_11[_i]; var expression = transformInitializedProperty(property, receiver); expression.startsOnNewLine = true; ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); @@ -46117,14 +46446,14 @@ var ts; function serializeEntityNameAsExpression(node, useFallback) { switch (node.kind) { case 71: - var name = ts.getMutableClone(node); - name.flags &= ~8; - name.original = undefined; - name.parent = currentScope; + var name_44 = ts.getMutableClone(node); + name_44.flags &= ~8; + name_44.original = undefined; + name_44.parent = currentScope; if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_44), ts.createLiteral("undefined")), name_44); } - return name; + return name_44; case 143: return serializeQualifiedNameAsExpression(node, useFallback); } @@ -46389,24 +46718,24 @@ var ts; && moduleKind !== ts.ModuleKind.System); } function recordEmittedDeclarationInScope(node) { - var name = node.symbol && node.symbol.escapedName; - if (name) { - if (!currentScopeFirstDeclarationsOfName) { - currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); - } - if (!currentScopeFirstDeclarationsOfName.has(name)) { - currentScopeFirstDeclarationsOfName.set(name, node); - } + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); + } + var name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); } } function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name = node.symbol && node.symbol.escapedName; - if (name) { - return currentScopeFirstDeclarationsOfName.get(name) === node; - } + var name_45 = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name_45) === node; } - return false; + return true; + } + function declaredNameInScope(node) { + ts.Debug.assertNode(node.name, ts.isIdentifier); + return node.name.escapedText; } function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ @@ -46437,7 +46766,7 @@ var ts; if (!shouldEmitModuleDeclaration(node)) { return ts.createNotEmittedStatement(node); } - ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); + ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); enableSubstitutionForNamespaceExports(); var statements = []; var emitFlags = 2; @@ -46699,14 +47028,14 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2) { - var name = node.name; - var exportedName = trySubstituteNamespaceExportedName(name); + var name_46 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_46); if (exportedName) { if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); + return ts.setTextRange(ts.createPropertyAssignment(name_46, initializer), node); } - return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node); + return ts.setTextRange(ts.createPropertyAssignment(name_46, exportedName), node); } } return node; @@ -47161,6 +47490,8 @@ var ts; return visitExpressionStatement(node); case 185: return visitParenthesizedExpression(node, noDestructuringValue); + case 260: + return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); } @@ -47235,6 +47566,12 @@ var ts; function visitParenthesizedExpression(node, noDestructuringValue) { return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } function visitBinaryExpression(node, noDestructuringValue) { if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576) { return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); @@ -47681,7 +48018,7 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -47767,12 +48104,12 @@ var ts; return getTagName(node.openingElement); } else { - var name = node.tagName; - if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + var name_47 = node.tagName; + if (ts.isIdentifier(name_47) && ts.isIntrinsicJsxName(name_47.escapedText)) { + return ts.createLiteral(ts.unescapeLeadingUnderscores(name_47.escapedText)); } else { - return ts.createExpressionFromEntityName(name); + return ts.createExpressionFromEntityName(name_47); } } } @@ -48268,7 +48605,7 @@ var ts; function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 && ts.isStatement(node)) + || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 207))) || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) || isTypeScriptClassWrapper(node); } @@ -48548,9 +48885,11 @@ var ts; var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); ts.setEmitFlags(outer, 1536); - return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement + var result = ts.createParen(ts.createCall(outer, undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); + ts.addSyntheticLeadingComment(result, 3, "* @class "); + return result; } function transformClassBody(node, extendsClauseElement) { var statements = []; @@ -48732,15 +49071,15 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_48 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + if (ts.isBindingPattern(name_48)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_48, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_48, initializer); } } } @@ -49135,11 +49474,12 @@ var ts; ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); if (node.transformFlags & 8388608 - && (ts.isBindingPattern(node.declarations[0].name) - || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + if (firstDeclaration) { + var lastDeclaration = ts.lastOrUndefined(declarations); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } } return declarationList; } @@ -49678,6 +50018,7 @@ var ts; function visitCatchClause(node) { var ancestorFacts = enterSubtree(4032, 0); var updated; + ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); if (ts.isBindingPattern(node.variableDeclaration.name)) { var temp = ts.createTempVariable(undefined); var newVariableDeclaration = ts.createVariableDeclaration(temp); @@ -50712,9 +51053,9 @@ var ts; function transformAndEmitVariableDeclarationList(node) { for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { var variable = _a[_i]; - var name = ts.getSynthesizedClone(variable.name); - ts.setCommentRange(name, variable.name); - hoistVariableDeclaration(name); + var name_49 = ts.getSynthesizedClone(variable.name); + ts.setCommentRange(name_49, variable.name); + hoistVariableDeclaration(name_49); } var variables = ts.getInitializedVariables(node); var numVariables = variables.length; @@ -50925,8 +51266,12 @@ var ts; } function transformAndEmitContinueStatement(node) { var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); - ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); - emitBreak(label, node); + if (label > 0) { + emitBreak(label, node); + } + else { + emitStatement(node); + } } function visitContinueStatement(node) { if (inStatementContainingYield) { @@ -50939,8 +51284,12 @@ var ts; } function transformAndEmitBreakStatement(node) { var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); - ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); - emitBreak(label, node); + if (label > 0) { + emitBreak(label, node); + } + else { + emitStatement(node); + } } function visitBreakStatement(node) { if (inStatementContainingYield) { @@ -51109,9 +51458,9 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; - if (name) { - var clone_6 = ts.getMutableClone(name); + var name_50 = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; + if (name_50) { + var clone_6 = ts.getMutableClone(name_50); ts.setSourceMapRange(clone_6, node); ts.setCommentRange(clone_6, node); return clone_6; @@ -51197,9 +51546,6 @@ var ts; var block = endBlock(); markLabel(block.endLabel); } - function isWithBlock(block) { - return block.kind === 1; - } function beginExceptionBlock() { var startLabel = defineLabel(); var endLabel = defineLabel(); @@ -51268,9 +51614,6 @@ var ts; emitNop(); exception.state = 3; } - function isExceptionBlock(block) { - return block.kind === 0; - } function beginScriptLoopBlock() { beginBlock({ kind: 3, @@ -51370,43 +51713,45 @@ var ts; return false; } function findBreakTarget(labelText) { - ts.Debug.assert(blocks !== undefined); - if (labelText) { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { - return block.breakLabel; - } - else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { - return block.breakLabel; + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } } } - } - else { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledBreak(block)) { - return block.breakLabel; + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } } } } return 0; } function findContinueTarget(labelText) { - ts.Debug.assert(blocks !== undefined); - if (labelText) { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { - return block.continueLabel; + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } } } - } - else { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledContinue(block)) { - return block.continueLabel; + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } } } } @@ -51434,7 +51779,7 @@ var ts; return literal; } function createInlineBreak(label, location) { - ts.Debug.assert(label > 0, "Invalid label: " + label); + ts.Debug.assertLessThan(0, label, "Invalid label"); return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ createInstruction(3), createLabel(label) @@ -51642,31 +51987,33 @@ var ts; for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { var block = blocks[blockIndex]; var blockAction = blockActions[blockIndex]; - if (isExceptionBlock(block)) { - if (blockAction === 0) { - if (!exceptionBlockStack) { - exceptionBlockStack = []; + switch (block.kind) { + case 0: + if (blockAction === 0) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; } - if (!statements) { - statements = []; + else if (blockAction === 1) { + currentExceptionBlock = exceptionBlockStack.pop(); } - exceptionBlockStack.push(currentExceptionBlock); - currentExceptionBlock = block; - } - else if (blockAction === 1) { - currentExceptionBlock = exceptionBlockStack.pop(); - } - } - else if (isWithBlock(block)) { - if (blockAction === 0) { - if (!withBlockStack) { - withBlockStack = []; + break; + case 1: + if (blockAction === 0) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); } - withBlockStack.push(block); - } - else if (blockAction === 1) { - withBlockStack.pop(); - } + else if (blockAction === 1) { + withBlockStack.pop(); + } + break; } } } @@ -52501,8 +52848,8 @@ var ts; return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), node); } else if (ts.isImportSpecifier(importDeclaration)) { - var name = importDeclaration.propertyName || importDeclaration.name; - return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), node); + var name_51 = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name_51)), node); } } } @@ -53976,7 +54323,6 @@ var ts; errorNameNode = declaration.name; var format = 4 | 16384 | - 2048 | (shouldUseResolverType ? 8192 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; @@ -53990,7 +54336,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 2048 | 16384, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 16384, writer); errorNameNode = undefined; } } @@ -54205,9 +54551,9 @@ var ts; var count = 0; while (true) { count++; - var name = baseName + "_" + count; - if (!currentIdentifiers.has(name)) { - return name; + var name_52 = baseName + "_" + count; + if (!currentIdentifiers.has(name_52)) { + return name_52; } } } @@ -54220,7 +54566,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 2048 | 16384, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 16384, writer); write(";"); writeLine(); return tempVarName; @@ -54857,6 +55203,9 @@ var ts; return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); } function writeVariableStatement(node) { + if (ts.every(node.declarationList && node.declarationList.declarations, function (decl) { return decl.name && ts.isEmptyBindingPattern(decl.name); })) { + return; + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.isLet(node.declarationList)) { @@ -55822,14 +56171,14 @@ var ts; writer.writeLine(); } } - function emitTrailingCommentsOfPosition(pos) { + function emitTrailingCommentsOfPosition(pos, prefixSpace) { if (disabled) { return; } if (extendedDiagnostics) { ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); } - forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); if (extendedDiagnostics) { ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); } @@ -55909,15 +56258,7 @@ var ts; emitPos(commentEnd); } function isTripleSlashComment(commentPos, commentEnd) { - if (currentText.charCodeAt(commentPos + 1) === 47 && - commentPos + 2 < commentEnd && - currentText.charCodeAt(commentPos + 2) === 47) { - var textSubStr = currentText.substring(commentPos, commentEnd); - return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || - textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? - true : false; - } - return false; + return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); } } ts.createCommentWriter = createCommentWriter; @@ -56856,7 +57197,9 @@ var ts; if (!(ts.getEmitFlags(node) & 131072)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = { kind: 23, pos: dotRangeStart, end: dotRangeEnd }; + var dotToken = ts.createToken(23); + dotToken.pos = dotRangeStart; + dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } @@ -56968,7 +57311,9 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + emitLeadingCommentsOfPosition(node.operatorToken.pos); writeTokenNode(node.operatorToken); + emitTrailingCommentsOfPosition(node.operatorToken.end, true); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -57155,8 +57500,19 @@ var ts; emitWithPrefix(" ", node.label); write(";"); } + function emitTokenWithComment(token, pos, contextNode) { + var node = contextNode && ts.getParseTreeNode(contextNode); + if (node && node.kind === contextNode.kind) { + pos = ts.skipTrivia(currentSourceFile.text, pos); + } + pos = writeToken(token, pos, contextNode); + if (node && node.kind === contextNode.kind) { + emitTrailingCommentsOfPosition(pos, true); + } + return pos; + } function emitReturnStatement(node) { - writeToken(96, node.pos, node); + emitTokenWithComment(96, node.pos, node); emitExpressionWithPrefix(" ", node.expression); write(";"); } @@ -57597,10 +57953,12 @@ var ts; function emitCatchClause(node) { var openParenPos = writeToken(74, node.pos); write(" "); - writeToken(19, openParenPos); - emit(node.variableDeclaration); - writeToken(20, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); - write(" "); + if (node.variableDeclaration) { + writeToken(19, openParenPos); + emit(node.variableDeclaration); + writeToken(20, node.variableDeclaration.end); + write(" "); + } emit(node.block); } function emitPropertyAssignment(node) { @@ -58154,21 +58512,21 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name)) { + var name_53 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_53)) { tempFlags |= flags; - return name; + return name_53; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name = count < 26 + var name_54 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name)) { - return name; + if (isUniqueName(name_54)) { + return name_54; } } } @@ -58651,13 +59009,13 @@ var ts; var resolutions = []; var cache = ts.createMap(); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name = names_1[_i]; + var name_55 = names_1[_i]; var result = void 0; - if (cache.has(name)) { - result = cache.get(name); + if (cache.has(name_55)) { + result = cache.get(name_55); } else { - cache.set(name, result = loader(name, containingFile)); + cache.set(name_55, result = loader(name_55, containingFile)); } resolutions.push(result); } @@ -58712,6 +59070,9 @@ var ts; var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } + var packageIdToSourceFile = ts.createMap(); + var sourceFileToPackageName = ts.createMap(); + var redirectTargetsSet = ts.createMap(); var filesByName = ts.createMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; var structuralIsReused = tryReuseStructureFromOldProgram(); @@ -58768,6 +59129,8 @@ var ts; isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsSet: redirectTargetsSet, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -58911,17 +59274,51 @@ var ts; var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2; - for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { - var oldSourceFile = _a[_i]; + var oldSourceFiles = oldProgram.getSourceFiles(); + var SeenPackageName; + (function (SeenPackageName) { + SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; + SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; + })(SeenPackageName || (SeenPackageName = {})); + var seenPackageNames = ts.createMap(); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { return oldProgram.structureIsReused = 0; } + ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + var fileChanged = void 0; + if (oldSourceFile.redirectInfo) { + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + return oldProgram.structureIsReused = 0; + } + fileChanged = false; + newSourceFile = oldSourceFile; + } + else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + if (newSourceFile !== oldSourceFile) { + return oldProgram.structureIsReused = 0; + } + fileChanged = false; + } + else { + fileChanged = newSourceFile !== oldSourceFile; + } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); - if (oldSourceFile !== newSourceFile) { + var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== undefined) { + var prevKind = seenPackageNames.get(packageName); + var newKind = fileChanged ? 1 : 0; + if ((prevKind !== undefined && newKind === 1) || prevKind === 1) { + return oldProgram.structureIsReused = 0; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { oldProgram.structureIsReused = 1; } @@ -58949,8 +59346,8 @@ var ts; 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; + for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { + var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); @@ -58984,8 +59381,8 @@ var ts; if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { return oldProgram.structureIsReused = 1; } - for (var _d = 0, _e = oldProgram.getMissingFilePaths(); _d < _e.length; _d++) { - var p = _e[_d]; + for (var _c = 0, _d = oldProgram.getMissingFilePaths(); _c < _d.length; _c++) { + var p = _d[_c]; filesByName.set(p, undefined); } for (var i = 0; i < newSourceFiles.length; i++) { @@ -58993,11 +59390,13 @@ var ts; } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _f = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _f < modifiedSourceFiles_2.length; _f++) { - var modifiedFile = modifiedSourceFiles_2[_f]; + for (var _e = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _e < modifiedSourceFiles_2.length; _e++) { + var modifiedFile = modifiedSourceFiles_2[_e]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsSet = oldProgram.redirectTargetsSet; return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { @@ -59476,7 +59875,7 @@ var ts; } } function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, undefined); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -59493,7 +59892,24 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + var redirect = Object.create(redirectTarget); + redirect.fileName = fileName; + redirect.path = path; + redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + Object.defineProperties(redirect, { + id: { + get: function () { return this.redirectInfo.redirectTarget.id; }, + set: function (value) { this.redirectInfo.redirectTarget.id = value; }, + }, + symbol: { + get: function () { return this.redirectInfo.redirectTarget.symbol; }, + set: function (value) { this.redirectInfo.redirectTarget.symbol = value; }, + }, + }); + return redirect; + } + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) { if (filesByName.has(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { @@ -59524,6 +59940,22 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + if (packageId) { + var packageIdKey = packageId.name + "@" + packageId.version; + var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); + redirectTargetsSet.set(fileFromPackageId.path, true); + filesByName.set(path, dupFile); + sourceFileToPackageName.set(path, packageId.name); + files.push(dupFile); + return dupFile; + } + else if (file) { + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageId.name); + } + } filesByName.set(path, file); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); @@ -59645,7 +60077,7 @@ var ts; else if (shouldAddFile) { var path = toPath(resolvedFileName); var pos = ts.skipTrivia(file.text, file.imports[i].pos); - findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end); + findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end, resolution.packageId); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -60758,7 +61190,9 @@ var ts; } ts.findNextToken = findNextToken; function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { - return find(startNode || sourceFile); + var result = find(startNode || sourceFile); + ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); + return result; function findRightmostToken(n) { if (ts.isToken(n)) { return n; @@ -60774,10 +61208,11 @@ var ts; var children = n.getChildren(); for (var i = 0; i < children.length; i++) { var child = children[i]; - if (position < child.end && (nodeHasTokens(child) || child.kind === 10)) { + if (position < child.end) { var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || - (child.kind === 10 && start === child.end); + !nodeHasTokens(child) || + isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { var candidate = findRightmostChildNodeWithTokens(children, i); return candidate && findRightmostToken(candidate); @@ -60795,7 +61230,11 @@ var ts; } function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { for (var i = exclusiveStartPosition - 1; i >= 0; i--) { - if (nodeHasTokens(children[i])) { + var child = children[i]; + if (isWhiteSpaceOnlyJsxText(child)) { + ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + } + else if (nodeHasTokens(children[i])) { return children[i]; } } @@ -60840,34 +61279,19 @@ var ts; return false; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isWhiteSpaceOnlyJsxText(node) { + return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; + } + ts.isWhiteSpaceOnlyJsxText = isWhiteSpaceOnlyJsxText; function isInTemplateString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position, false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; function isInComment(sourceFile, position, tokenAtPosition, predicate) { - if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, false); } - return position <= tokenAtPosition.getStart(sourceFile) && - (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || - isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); - function isInCommentRange(commentRanges) { - return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); - } + return !!ts.formatting.getRangeOfEnclosingComment(sourceFile, position, false, undefined, tokenAtPosition, predicate); } 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; - } - } function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position, false); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); @@ -61220,6 +61644,7 @@ var ts; } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + flags |= 65536; return mapToDisplayParts(function (writer) { typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); }); @@ -61925,11 +62350,11 @@ var ts; templateStack.pop(); } else { - ts.Debug.assert(token === 15, "Should have been a template middle. Was " + token); + ts.Debug.assertEqual(token, 15, "Should have been a template middle."); } } else { - ts.Debug.assert(lastTemplateStackToken === 17, "Should have been an open brace. Was: " + token); + ts.Debug.assertEqual(lastTemplateStackToken, 17, "Should have been an open brace"); templateStack.pop(); } } @@ -62791,11 +63216,11 @@ var ts; if (currentConfigPath) { paths.push(currentConfigPath); currentDir = ts.getDirectoryPath(currentConfigPath); - var parent = ts.getDirectoryPath(currentDir); - if (currentDir === parent) { + var parent_18 = ts.getDirectoryPath(currentDir); + if (currentDir === parent_18) { break; } - currentDir = parent; + currentDir = parent_18; } else { break; @@ -63102,11 +63527,11 @@ var ts; } } else if (type.flags & 32) { - var name = type.value; - if (!uniques.has(name)) { - uniques.set(name, true); + var name_56 = type.value; + if (!uniques.has(name_56)) { + uniques.set(name_56, true); result.push({ - name: name, + name: name_56, kindModifiers: "", kind: "var", sortText: "0" @@ -63117,10 +63542,10 @@ var ts; function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location = completionData.location; + var symbols = completionData.symbols, location_3 = completionData.location; var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), @@ -63217,13 +63642,13 @@ var ts; log("Returning an empty list because completion was requested in an invalid position."); return undefined; } - var parent = contextToken.parent; + var parent_19 = contextToken.parent; if (contextToken.kind === 23) { - if (parent.kind === 179) { + if (parent_19.kind === 179) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent.kind === 143) { + else if (parent_19.kind === 143) { node = contextToken.parent.left; isRightOfDot = true; } @@ -63232,11 +63657,11 @@ var ts; } } else if (sourceFile.languageVariant === 1) { - if (parent && parent.kind === 179) { - contextToken = parent; - parent = parent.parent; + if (parent_19 && parent_19.kind === 179) { + contextToken = parent_19; + parent_19 = parent_19.parent; } - switch (parent.kind) { + switch (parent_19.kind) { case 252: if (contextToken.kind === 41) { isStartingCloseTag = true; @@ -63244,7 +63669,7 @@ var ts; } break; case 194: - if (!(parent.left.flags & 32768)) { + if (!(parent_19.left.flags & 32768)) { break; } case 250: @@ -63587,7 +64012,7 @@ var ts; var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); if (!typeForObject) return false; - typeMembers = typeChecker.getPropertiesOfType(typeForObject); + typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24); }); existingMembers = objectLikeContainer.elements; } } @@ -63657,9 +64082,9 @@ var ts; switch (contextToken.kind) { case 17: case 26: - var parent = contextToken.parent; - if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { - return parent; + var parent_20 = contextToken.parent; + if (ts.isObjectLiteralExpression(parent_20) || ts.isObjectBindingPattern(parent_20)) { + return parent_20; } break; } @@ -63739,7 +64164,7 @@ var ts; } function tryGetContainingJsxElement(contextToken) { if (contextToken) { - var parent = contextToken.parent; + var parent_21 = contextToken.parent; switch (contextToken.kind) { case 28: case 41: @@ -63748,26 +64173,26 @@ var ts; case 254: case 253: case 255: - if (parent && (parent.kind === 250 || parent.kind === 251)) { - return parent; + if (parent_21 && (parent_21.kind === 250 || parent_21.kind === 251)) { + return parent_21; } - else if (parent.kind === 253) { - return parent.parent.parent; + else if (parent_21.kind === 253) { + return parent_21.parent.parent; } break; case 9: - if (parent && ((parent.kind === 253) || (parent.kind === 255))) { - return parent.parent.parent; + if (parent_21 && ((parent_21.kind === 253) || (parent_21.kind === 255))) { + return parent_21.parent.parent; } break; case 18: - if (parent && - parent.kind === 256 && - parent.parent && parent.parent.kind === 253) { - return parent.parent.parent.parent; + if (parent_21 && + parent_21.kind === 256 && + parent_21.parent && parent_21.parent.kind === 253) { + return parent_21.parent.parent.parent; } - if (parent && parent.kind === 255) { - return parent.parent.parent; + if (parent_21 && parent_21.kind === 255) { + return parent_21.parent.parent; } break; } @@ -63892,8 +64317,8 @@ var ts; if (isCurrentlyEditingNode(element)) { continue; } - var name = element.propertyName || element.name; - existingImportsOrExports.set(name.escapedText, true); + var name_57 = element.propertyName || element.name; + existingImportsOrExports.set(name_57.escapedText, true); } if (existingImportsOrExports.size === 0) { return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default"; }); @@ -63925,8 +64350,8 @@ var ts; } } else { - var name = ts.getNameOfDeclaration(m); - existingName = ts.getEscapedTextOfIdentifierOrLiteral(name); + var name_58 = ts.getNameOfDeclaration(m); + existingName = ts.getEscapedTextOfIdentifierOrLiteral(name_58); } existingMemberNames.set(existingName, true); } @@ -63964,8 +64389,8 @@ var ts; addPropertySymbols(implementingTypeSymbols, 24); return result; function addPropertySymbols(properties, inValidModifierFlags) { - for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { - var property = properties_11[_i]; + for (var _i = 0, properties_12 = properties; _i < properties_12.length; _i++) { + var property = properties_12[_i]; if (isValidProperty(property, inValidModifierFlags)) { result.push(property); } @@ -64282,17 +64707,17 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_2 = child.parent; - if (ts.isFunctionBlock(parent_2) || parent_2.kind === 265) { - return parent_2; + var parent_22 = child.parent; + if (ts.isFunctionBlock(parent_22) || parent_22.kind === 265) { + return parent_22; } - if (parent_2.kind === 224) { - var tryStatement = parent_2; + if (parent_22.kind === 224) { + var tryStatement = parent_22; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_2; + child = parent_22; } return undefined; } @@ -64763,11 +65188,11 @@ var ts; switch (direct.kind) { case 181: if (!isAvailableThroughGlobal) { - var parent = direct.parent; - if (exportKind === 2 && parent.kind === 226) { - var name = parent.name; - if (name.kind === 71) { - directImports.push(name); + var parent_23 = direct.parent; + if (exportKind === 2 && parent_23.kind === 226) { + var name_59 = parent_23.name; + if (name_59.kind === 71) { + directImports.push(name_59); break; } } @@ -64884,10 +65309,10 @@ var ts; searchForNamedImport(namedBindings); } else { - var name = importClause.name; - if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) { - var defaultImportAlias = checker.getSymbolAtLocation(name); - addSearch(name, defaultImportAlias); + var name_60 = importClause.name; + if (name_60 && (!isForRename || name_60.escapedText === symbolName(exportSymbol))) { + var defaultImportAlias = checker.getSymbolAtLocation(name_60); + addSearch(name_60, defaultImportAlias); } if (!isForRename && exportKind === 1) { ts.Debug.assert(exportName === "default"); @@ -64904,21 +65329,21 @@ var ts; if (namedBindings) { for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var element = _a[_i]; - var name = element.name, propertyName = element.propertyName; - if ((propertyName || name).escapedText !== exportName) { + var name_61 = element.name, propertyName = element.propertyName; + if ((propertyName || name_61).escapedText !== exportName) { continue; } if (propertyName) { singleReferences.push(propertyName); if (!isForRename) { - addSearch(name, checker.getSymbolAtLocation(name)); + addSearch(name_61, checker.getSymbolAtLocation(name_61)); } } else { var localSymbol = element.kind === 246 && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) - : checker.getSymbolAtLocation(name); - addSearch(name, localSymbol); + : checker.getSymbolAtLocation(name_61); + addSearch(name_61, localSymbol); } } } @@ -65288,8 +65713,8 @@ var ts; case "symbol": { var symbol = def.symbol, node_2 = def.node; 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 }; + var name_62 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_2, name: name_62, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_3 = def.node; @@ -65297,8 +65722,8 @@ var ts; } case "keyword": { var node_4 = def.node; - var name_4 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_4, kind: "keyword", displayParts: [{ text: name_4, kind: "keyword" }] }; + var name_63 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_63, kind: "keyword", displayParts: [{ text: name_63, kind: "keyword" }] }; } case "this": { var node_5 = def.node; @@ -65655,11 +66080,15 @@ var ts; } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - if (bindingElement) { - var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + if (!bindingElement) + return undefined; + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + if (propSymbol && propSymbol.flags & 98304) { + ts.Debug.assert(!!(propSymbol.flags & 33554432)); + return propSymbol.target; } - return undefined; + return propSymbol; } function getSymbolScope(symbol) { var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; @@ -65679,12 +66108,13 @@ var ts; if (getObjectBindingElementWithoutPropertyName(symbol)) { return undefined; } - if (parent && !((parent.flags & 1536) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + var exposedByParent = parent && !(symbol.flags & 262144); + if (exposedByParent && !((parent.flags & 1536) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { return undefined; @@ -65694,7 +66124,7 @@ var ts; } scope = container; } - return parent ? scope.getSourceFile() : scope; + return exposedByParent ? scope.getSourceFile() : scope; } function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } @@ -65970,12 +66400,12 @@ var ts; } var containingTypeReference = getContainingTypeReference(refNode); if (containingTypeReference && state.markSeenContainingTypeReference(containingTypeReference)) { - var parent = containingTypeReference.parent; - if (ts.isVariableLike(parent) && parent.type === containingTypeReference && parent.initializer && isImplementationExpression(parent.initializer)) { - addReference(parent.initializer); + var parent_24 = containingTypeReference.parent; + if (ts.isVariableLike(parent_24) && parent_24.type === containingTypeReference && parent_24.initializer && isImplementationExpression(parent_24.initializer)) { + addReference(parent_24.initializer); } - else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { - var body = parent.body; + else if (ts.isFunctionLike(parent_24) && parent_24.type === containingTypeReference && parent_24.body) { + var body = parent_24.body; if (body.kind === 207) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { @@ -65987,8 +66417,8 @@ var ts; addReference(body); } } - else if (ts.isAssertionExpression(parent) && isImplementationExpression(parent.expression)) { - addReference(parent.expression); + else if (ts.isAssertionExpression(parent_24) && isImplementationExpression(parent_24.expression)) { + addReference(parent_24.expression); } } } @@ -66371,8 +66801,8 @@ var ts; var lastIterationMeaning = void 0; do { lastIterationMeaning = meaning; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -66517,6 +66947,16 @@ 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.isPropertyName(node) && ts.isBindingElement(node.parent) && ts.isObjectBindingPattern(node.parent.parent) && + (node === (node.parent.propertyName || node.parent.name))) { + var type = typeChecker.getTypeAtLocation(node.parent.parent); + if (type) { + var propSymbols = ts.getPropertySymbolsFromType(type, node); + if (propSymbols) { + return ts.flatMap(propSymbols, function (propSymbol) { return getDefinitionFromSymbol(typeChecker, propSymbol, node); }); + } + } + } var element = ts.getContainingObjectLiteralElement(node); if (element && typeChecker.getContextualType(element.parent)) { return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { @@ -66933,12 +67373,20 @@ var ts; "crypto", "stream", "util", "assert", "tty", "domain", "constants", "process", "v8", "timers", "console" ]; - var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); + var nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); function loadSafeList(host, safeListPath) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); return ts.createMapFromTemplate(result.config); } JsTyping.loadSafeList = loadSafeList; + function loadTypesMap(host, typesMapPath) { + var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); + if (result.config) { + return ts.createMapFromTemplate(result.config.simpleMap); + } + return undefined; + } + JsTyping.loadTypesMap = loadTypesMap; function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; @@ -67093,8 +67541,8 @@ var ts; if (!matches) { return; } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; if (patternMatcher.patternContainsDots) { var containers = getContainers(declaration); if (!containers) { @@ -67145,14 +67593,14 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - var text = ts.getTextOfIdentifierOrLiteral(name); + var name_64 = ts.getNameOfDeclaration(declaration); + if (name_64) { + var text = ts.getTextOfIdentifierOrLiteral(name_64); if (text !== undefined) { containers.unshift(text); } - else if (name.kind === 144) { - return tryAddComputedPropertyName(name.expression, containers, true); + else if (name_64.kind === 144) { + return tryAddComputedPropertyName(name_64.expression, containers, true); } else { return false; @@ -67378,9 +67826,9 @@ var ts; case 176: case 226: var decl = node; - var name = decl.name; - if (ts.isBindingPattern(name)) { - addChildrenRecursively(name); + var name_65 = decl.name; + if (ts.isBindingPattern(name_65)) { + addChildrenRecursively(name_65); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { addChildrenRecursively(decl.initializer); @@ -67753,13 +68201,17 @@ var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { + var collapseText = "..."; + var maxDepth = 20; function collectElements(sourceFile, cancellationToken) { var elements = []; - var collapseText = "..."; - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { + var depth = 0; + walk(sourceFile); + return elements; + function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { if (hintSpanNode && startElement && endElement) { var span_13 = { - textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), + textSpan: ts.createTextSpanFromBounds(useFullStart ? startElement.getFullStart() : startElement.getStart(), endElement.getEnd()), hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), bannerText: collapseText, autoCollapse: autoCollapse, @@ -67820,8 +68272,6 @@ var ts; function autoCollapse(node) { return ts.isFunctionBlock(node) && node.parent.kind !== 187; } - var depth = 0; - var maxDepth = 20; function walk(n) { cancellationToken.throwIfCancellationRequested(); if (depth > maxDepth) { @@ -67833,30 +68283,30 @@ var ts; switch (n.kind) { case 207: if (!ts.isFunctionBlock(n)) { - var parent = n.parent; - var openBrace = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18, sourceFile); - if (parent.kind === 212 || - parent.kind === 215 || - parent.kind === 216 || - parent.kind === 214 || - parent.kind === 211 || - parent.kind === 213 || - parent.kind === 220 || - parent.kind === 260) { - addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + var parent_25 = n.parent; + var openBrace_1 = ts.findChildOfKind(n, 17, sourceFile); + var closeBrace_1 = ts.findChildOfKind(n, 18, sourceFile); + if (parent_25.kind === 212 || + parent_25.kind === 215 || + parent_25.kind === 216 || + parent_25.kind === 214 || + parent_25.kind === 211 || + parent_25.kind === 213 || + parent_25.kind === 220 || + parent_25.kind === 260) { + addOutliningSpan(parent_25, openBrace_1, closeBrace_1, autoCollapse(n), true); break; } - if (parent.kind === 224) { - var tryStatement = parent; + if (parent_25.kind === 224) { + var tryStatement = parent_25; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_25, openBrace_1, closeBrace_1, autoCollapse(n), true); break; } else if (tryStatement.finallyBlock === n) { var finallyKeyword = ts.findChildOfKind(tryStatement, 87, sourceFile); if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(finallyKeyword, openBrace_1, closeBrace_1, autoCollapse(n), true); break; } } @@ -67871,33 +68321,35 @@ var ts; break; } case 234: { - var openBrace = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18, sourceFile); - addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + var openBrace_2 = ts.findChildOfKind(n, 17, sourceFile); + var closeBrace_2 = ts.findChildOfKind(n, 18, sourceFile); + addOutliningSpan(n.parent, openBrace_2, closeBrace_2, autoCollapse(n), true); break; } case 229: case 230: case 232: - case 178: case 235: { - var openBrace = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); + var openBrace_3 = ts.findChildOfKind(n, 17, sourceFile); + var closeBrace_3 = ts.findChildOfKind(n, 18, sourceFile); + addOutliningSpan(n, openBrace_3, closeBrace_3, autoCollapse(n), true); break; } + case 178: + var openBrace = ts.findChildOfKind(n, 17, sourceFile); + var closeBrace = ts.findChildOfKind(n, 18, sourceFile); + addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n), !ts.isArrayLiteralExpression(n.parent)); + break; case 177: var openBracket = ts.findChildOfKind(n, 21, sourceFile); var closeBracket = ts.findChildOfKind(n, 22, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); + addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n), !ts.isArrayLiteralExpression(n.parent)); break; } depth++; ts.forEachChild(n, walk); depth--; } - walk(sourceFile); - return elements; } OutliningElementsCollector.collectElements = collectElements; })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); @@ -68741,8 +69193,8 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - for (var _b = 0, declarations_13 = declarations; _b < declarations_13.length; _b++) { - var declaration = declarations_13[_b]; + for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { + var declaration = declarations_12[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -68775,7 +69227,9 @@ var ts; } var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 : 1; var argumentCount = getArgumentCount(list); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } @@ -68853,7 +69307,9 @@ var ts; var argumentCount = tagExpression.template.kind === 13 ? 1 : tagExpression.template.templateSpans.length + 1; - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } return { kind: 2, invocation: tagExpression, @@ -68950,7 +69406,9 @@ var ts; tags: candidateSignature.getJsDocTags() }; }); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } var selectedItemIndex = candidates.indexOf(resolvedSignature); ts.Debug.assert(selectedItemIndex !== -1); return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; @@ -69091,102 +69549,100 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (type) { - if (location.parent && location.parent.kind === 179) { - var right = location.parent.name; - if (right === location || (right && right.getFullWidth() === 0)) { - location = location.parent; + if (location.parent && location.parent.kind === 179) { + var right = location.parent.name; + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + var callExpressionLike = void 0; + if (ts.isCallOrNewExpression(location)) { + callExpressionLike = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpressionLike = location.parent; + } + else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { + callExpressionLike = location.parent; + } + if (callExpressionLike) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); + if (!signature && candidateSignatures.length) { + signature = candidateSignatures[0]; + } + var useConstructSignatures = callExpressionLike.kind === 182 || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97); + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32)) { + symbolKind = "constructor"; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } - } - var callExpressionLike = void 0; - if (ts.isCallOrNewExpression(location)) { - callExpressionLike = location; - } - else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { - callExpressionLike = location.parent; - } - else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { - callExpressionLike = location.parent; - } - if (callExpressionLike) { - var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); - if (!signature && candidateSignatures.length) { - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpressionLike.kind === 182 || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97); - var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { - signature = allSignatures.length ? allSignatures[0] : undefined; - } - if (signature) { - if (useConstructSignatures && (symbolFlags & 32)) { - symbolKind = "constructor"; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + else if (symbolFlags & 2097152) { + symbolKind = "alias"; + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(94)); + displayParts.push(ts.spacePart()); } - else if (symbolFlags & 2097152) { - symbolKind = "alias"; - pushTypePart(symbolKind); + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case "JSX attribute": + case "property": + case "var": + case "const": + case "let": + case "parameter": + case "local var": + displayParts.push(ts.punctuationPart(56)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { displayParts.push(ts.keywordPart(94)); displayParts.push(ts.spacePart()); } - addFullSymbolName(symbol); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - switch (symbolKind) { - case "JSX attribute": - case "property": - case "var": - case "const": - case "let": - case "parameter": - case "local var": - displayParts.push(ts.punctuationPart(56)); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94)); - displayParts.push(ts.spacePart()); - } - if (!(type.flags & 32768 && type.objectFlags & 16) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); - } - addSignatureDisplayParts(signature, allSignatures, 16); - break; - default: - addSignatureDisplayParts(signature, allSignatures); - } - hasAddedSymbolInfo = true; + if (!(type.flags & 32768 && type.objectFlags & 16) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); + } + addSignatureDisplayParts(signature, allSignatures, 16); + break; + default: + addSignatureDisplayParts(signature, allSignatures); } + hasAddedSymbolInfo = true; } - else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304)) || - (location.kind === 123 && location.parent.kind === 152)) { - 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 = "constructor"; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 && - !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304)) || + (location.kind === 123 && location.parent.kind === 152)) { + var functionDeclaration_1 = location.parent; + var locationIsSymbolDeclaration = ts.find(symbol.declarations, 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 = "constructor"; + 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; } } } @@ -69361,7 +69817,9 @@ var ts; symbolFlags & 98304 || symbolKind === "method") { var allSignatures = type.getNonNullableType().getCallSignatures(); - addSignatureDisplayParts(allSignatures[0], allSignatures); + if (allSignatures.length) { + addSignatureDisplayParts(allSignatures[0], allSignatures); + } } } } @@ -69464,8 +69922,8 @@ var ts; if (declaration.kind !== 226 && declaration.kind !== 228) { return false; } - for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { - if (parent.kind === 265 || parent.kind === 234) { + for (var parent_26 = declaration.parent; !ts.isFunctionBlock(parent_26); parent_26 = parent_26.parent) { + if (parent_26.kind === 265 || parent_26.kind === 234) { return false; } } @@ -69509,11 +69967,11 @@ var ts; getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, writeFile: function (name, text) { if (ts.fileExtensionIs(name, ".map")) { - ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); + ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name); sourceMapText = text; } else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); + ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name); outputText = text; } }, @@ -70132,6 +70590,7 @@ var ts; 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.SpaceBetweenOpenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 19), 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)); @@ -70203,7 +70662,7 @@ var ts; this.SpaceAfterComma, this.NoSpaceAfterComma, this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, - this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, + this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.SpaceBetweenOpenParens, 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, @@ -70227,9 +70686,9 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name in o) { - if (o[name] === rule) { - return name; + for (var name_66 in o) { + if (o[name_66] === rule) { + return name_66; } } throw new Error("Unknown rule"); @@ -71003,7 +71462,6 @@ var ts; } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); - var previousRangeHasError; var previousRange; var previousParent; var previousRangeStartLine; @@ -71339,7 +71797,7 @@ var ts; function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAdded; - if (!rangeHasError && !previousRangeHasError) { + if (!rangeHasError) { if (!previousRange) { var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); @@ -71352,7 +71810,6 @@ var ts; previousRange = range; previousParent = parent; previousRangeStartLine = rangeStart.line; - previousRangeHasError = rangeHasError; return lineAdded; } function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { @@ -71531,6 +71988,32 @@ var ts; } } } + function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, false); } + var tokenStart = tokenAtPosition.getStart(sourceFile); + if (tokenStart <= position && position < tokenAtPosition.getEnd()) { + return undefined; + } + if (precedingToken === undefined) { + precedingToken = ts.findPrecedingToken(position, sourceFile); + } + var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end); + var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); + var commentRanges = trailingRangesOfPreviousToken && leadingCommentRangesOfNextToken ? + trailingRangesOfPreviousToken.concat(leadingCommentRangesOfNextToken) : + trailingRangesOfPreviousToken || leadingCommentRangesOfNextToken; + if (commentRanges) { + for (var _i = 0, commentRanges_1 = commentRanges; _i < commentRanges_1.length; _i++) { + var range = commentRanges_1[_i]; + if ((range.pos < position && position < range.end || + position === range.end && (range.kind === 2 || position === sourceFile.getFullWidth()))) { + return (range.kind === 3 || !onlyMultiLine) && (!predicate || predicate(range)) ? range : undefined; + } + } + } + return undefined; + } + formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { case 152: @@ -71641,11 +72124,27 @@ var ts; return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, true, precedingToken || null); + if (enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 ? column - 1 : column; + } if (!precedingToken) { return getBaseIndentation(options); } var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); - if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) { + if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) { return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; @@ -72050,6 +72549,12 @@ var ts; } return false; } + var ChangeKind; + (function (ChangeKind) { + ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; + ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; + ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + })(ChangeKind || (ChangeKind = {})); function getSeparatorCharacter(separator) { return ts.tokenToString(separator.kind); } @@ -72074,7 +72579,7 @@ var ts; } textChanges.getAdjustedStartPosition = getAdjustedStartPosition; function getAdjustedEndPosition(sourceFile, node, options) { - if (options.useNonAdjustedEndPosition) { + if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { return node.getEnd(); } var end = node.getEnd(); @@ -72094,6 +72599,9 @@ var ts; } return s; } + function getNewlineKind(context) { + return context.newLineCharacter === "\n" ? 1 : 0; + } var ChangeTracker = (function () { function ChangeTracker(newLine, rulesProvider, validator) { this.newLine = newLine; @@ -72103,24 +72611,24 @@ var ts; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromCodeFixContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 : 0, context.rulesProvider); + return new ChangeTracker(getNewlineKind(context), context.rulesProvider); + }; + ChangeTracker.prototype.deleteRange = function (sourceFile, range) { + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); + return this; }; ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, node, options); - this.changes.push({ sourceFile: sourceFile, options: options, range: { pos: startPosition, end: endPosition } }); - return this; - }; - ChangeTracker.prototype.deleteRange = function (sourceFile, range) { - this.changes.push({ sourceFile: sourceFile, range: range }); + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); return this; }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, range: { pos: startPosition, end: endPosition } }); + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); return this; }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { @@ -72156,33 +72664,68 @@ var ts; }; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ sourceFile: sourceFile, range: range, options: options, node: newNode }); + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); return this; }; ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: endPosition } }); - return this; + return this.replaceWithSingle(sourceFile, startPosition, endPosition, newNode, options); }; ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: endPosition } }); + return this.replaceWithSingle(sourceFile, startPosition, endPosition, newNode, options); + }; + ChangeTracker.prototype.replaceWithSingle = function (sourceFile, startPosition, endPosition, newNode, options) { + this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, + sourceFile: sourceFile, + options: options, + node: newNode, + range: { pos: startPosition, end: endPosition } + }); return this; }; + ChangeTracker.prototype.replaceWithMultiple = function (sourceFile, startPosition, endPosition, newNodes, options) { + this.changes.push({ + kind: ChangeKind.ReplaceWithMultipleNodes, + sourceFile: sourceFile, + options: options, + nodes: newNodes, + range: { pos: startPosition, end: endPosition } + }); + return this; + }; + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; + ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, oldNodes[0], options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, ts.lastOrUndefined(oldNodes), options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; + ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { + return this.replaceWithMultiple(sourceFile, range.pos, range.end, newNodes, options); + }; + ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); return this; }; ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, before, options, Position.Start); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: startPosition } }); - return this; + return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, options); }; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { if (options === void 0) { options = {}; } @@ -72192,6 +72735,7 @@ var ts; after.kind === 150) { if (sourceFile.text.charCodeAt(after.end - 1) !== 59) { this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: {}, range: { pos: after.end, end: after.end }, @@ -72200,8 +72744,7 @@ var ts; } } var endPosition = getAdjustedEndPosition(sourceFile, after, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: endPosition, end: endPosition } }); - return this; + return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, options); }; ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) { var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); @@ -72229,10 +72772,10 @@ var ts; startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); } this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: startPos, end: containingList[index + 1].getStart(sourceFile) }, node: newNode, - useIndentationFromFile: true, options: { prefix: prefix, suffix: "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)) @@ -72259,6 +72802,7 @@ var ts; } if (multilineList) { this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: end, end: end }, node: ts.createToken(separator), @@ -72270,6 +72814,7 @@ var ts; insertPos--; } this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: insertPos, end: insertPos }, node: newNode, @@ -72278,6 +72823,7 @@ var ts; } else { this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: end, end: end }, node: newNode, @@ -72317,31 +72863,44 @@ var ts; return ts.createTextSpanFromBounds(change.range.pos, change.range.end); }; ChangeTracker.prototype.computeNewText = function (change, sourceFile) { - if (!change.node) { + var _this = this; + if (change.kind === ChangeKind.Remove) { return ""; } var options = change.options || {}; - var nonFormattedText = getNonformattedText(change.node, sourceFile, this.newLine); - if (this.validator) { - this.validator(nonFormattedText); - } - var formatOptions = this.rulesProvider.getFormatOptions(); + var text; var pos = change.range.pos; var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - var initialIndentation = change.options.indentation !== undefined - ? change.options.indentation - : change.useIndentationFromFile - ? ts.formatting.SmartIndenter.getIndentation(change.range.pos, sourceFile, formatOptions, posStartsLine || (change.options.prefix === this.newLineCharacter)) - : 0; - var delta = change.options.delta !== undefined - ? change.options.delta - : ts.formatting.SmartIndenter.shouldIndentChildNode(change.node) - ? formatOptions.indentSize - : 0; - var text = applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, this.rulesProvider); - text = posStartsLine || change.options.indentation !== undefined ? text : text.replace(/^\s+/, ""); + if (change.kind === ChangeKind.ReplaceWithMultipleNodes) { + var parts = change.nodes.map(function (n) { return _this.getFormattedTextOfNode(n, sourceFile, pos, options); }); + text = parts.join(change.options.nodeSeparator); + } + else { + ts.Debug.assert(change.kind === ChangeKind.ReplaceWithSingleNode, "change.kind === ReplaceWithSingleNode"); + text = this.getFormattedTextOfNode(change.node, sourceFile, pos, options); + } + text = (posStartsLine || options.indentation !== undefined) ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + text + (options.suffix || ""); }; + ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) { + var nonformattedText = getNonformattedText(node, sourceFile, this.newLine); + if (this.validator) { + this.validator(nonformattedText); + } + var formatOptions = this.rulesProvider.getFormatOptions(); + var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; + var initialIndentation = options.indentation !== undefined + ? options.indentation + : (options.useIndentationFromFile !== false) + ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter)) + : 0; + var delta = options.delta !== undefined + ? options.delta + : ts.formatting.SmartIndenter.shouldIndentChildNode(node) + ? (formatOptions.indentSize || 0) + : 0; + return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.rulesProvider); + }; ChangeTracker.normalize = function (changes) { var normalized = ts.stableSort(changes, function (a, b) { return a.range.pos - b.range.pos; }); for (var i = 0; i < normalized.length - 2; i++) { @@ -73319,7 +73878,7 @@ var ts; symbolName = name; } else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { - symbol = checker.getAliasedSymbol(checker.resolveNameAtLocation(token, checker.getJsxNamespace(), 107455)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455)); symbolName = symbol.name; } else { @@ -73403,8 +73962,8 @@ var ts; var namespaceImportDeclaration; var namedImportDeclaration; var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (declaration.kind === 238) { var namedBindings = declaration.importClause && declaration.importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { @@ -73478,14 +74037,53 @@ var ts; : isNamespaceImport ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))])); - var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); + moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); + var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, moduleSpecifierLiteral); if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeAt(sourceFile, getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); } else { changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); } return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getSourceFileImportLocation(node) { + var text = node.text; + var ranges = ts.getLeadingCommentRanges(text, 0); + if (!ranges) + return 0; + var position = 0; + if (ranges.length && ranges[0].kind === 3 && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end + 1; + ranges = ranges.slice(1); + } + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 && ts.isRecognizedTripleSlashComment(node.text, range.pos, range.end)) { + position = range.end + 1; + continue; + } + break; + } + return position; + } + function getSingleQuoteStyleFromExistingImports() { + var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { + if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { + if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { + return node.moduleSpecifier; + } + } + else if (ts.isImportEqualsDeclaration(node)) { + if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { + return node.moduleReference.expression; + } + } + }); + if (firstModuleSpecifier) { + return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39; + } + } function getModuleSpecifierForNewImport() { var fileName = sourceFile.fileName; var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; @@ -73615,7 +74213,8 @@ var ts; (function (States) { States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; States[States["NodeModules"] = 1] = "NodeModules"; - States[States["PackageContent"] = 2] = "PackageContent"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; })(States || (States = {})); var partStart = 0; var partEnd = 0; @@ -73632,15 +74231,21 @@ var ts; } break; case 1: - packageRootIndex = partEnd; - state = 2; - break; case 2: + if (state === 1 && fullPath.charAt(partStart + 1) === "@") { + state = 2; + } + else { + packageRootIndex = partEnd; + state = 3; + } + break; + case 3: if (fullPath.indexOf("/node_modules/", partStart) === partStart) { state = 1; } else { - state = 2; + state = 3; } break; } @@ -73867,8 +74472,8 @@ var ts; if (includeTypeScriptSyntax) { var typeArgCount = ts.length(callExpression.typeArguments); for (var i = 0; i < typeArgCount; i++) { - var name = typeArgCount < 8 ? String.fromCharCode(84 + i) : "T" + i; - var typeParameter = ts.createTypeParameterDeclaration(name, undefined, undefined); + var name_67 = typeArgCount < 8 ? String.fromCharCode(84 + i) : "T" + i; + var typeParameter = ts.createTypeParameterDeclaration(name_67, undefined, undefined); (typeParameters ? typeParameters : typeParameters = []).push(typeParameter); } } @@ -73930,206 +74535,1029 @@ var ts; (function (ts) { var refactor; (function (refactor) { - var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); - function getAvailableActions(context) { - if (!ts.isInJavaScriptFile(context.file)) { - return undefined; + var convertFunctionToES6Class; + (function (convertFunctionToES6Class_1) { + var actionName = "convert"; + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions + }; + refactor.registerRefactor(convertFunctionToES6Class); + function getAvailableActions(context) { + if (!ts.isInJavaScriptFile(context.file)) { + return undefined; + } + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start, false); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + if (symbol && (symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { + return [ + { + name: convertFunctionToES6Class.name, + description: convertFunctionToES6Class.description, + actions: [ + { + description: convertFunctionToES6Class.description, + name: actionName + } + ] + } + ]; + } } - var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start, false); - var checker = context.program.getTypeChecker(); - var symbol = checker.getSymbolAtLocation(node); - if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = symbol.valueDeclaration.initializer.symbol; - } - if (symbol && (symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { - return [ - { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, - actions: [ - { - description: convertFunctionToES6Class.description, - name: actionName - } - ] + function getEditsForAction(context, action) { + if (actionName !== action) { + return undefined; + } + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start, false); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 | 3))) { + return undefined; + } + 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 undefined; + } + 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 { + edits: changeTracker.getChanges() + }; + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + return; } - ]; - } - } - function getEditsForAction(context, action) { - if (actionName !== action) { - return undefined; - } - var start = context.startPosition; - var sourceFile = context.file; - var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start, false); - var ctorSymbol = checker.getSymbolAtLocation(token); - var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; - var deletedNodes = []; - var deletes = []; - if (!(ctorSymbol.flags & (16 | 3))) { - return undefined; - } - 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); + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); } else { - deleteNode(ctorDeclaration, true); + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); } - newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); - break; - } - if (!newClassDeclaration) { - return undefined; - } - 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 { - edits: 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); }); + 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; + var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + copyComments(assignmentBinaryExpression, method); + return method; + } + 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)]); + } + var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + copyComments(assignmentBinaryExpression, method); + return method; + } + default: { + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + var prop = ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop); + return prop; + } + } + } + } + function copyComments(sourceNode, targetNode) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3) { + pos += 2; + end -= 2; + } + else { + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + }); + } + 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)); + } + var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + return cls; + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); + } + var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + return cls; + } + } + })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var extractMethod; + (function (extractMethod_1) { + var extractMethod = { + name: "Extract Method", + description: ts.Diagnostics.Extract_function.message, + getAvailableActions: getAvailableActions, + getEditsForAction: getEditsForAction, + }; + refactor.registerRefactor(extractMethod); + function getAvailableActions(context) { + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: context.endPosition - context.startPosition }); + var targetRange = rangeToExtract.targetRange; + if (targetRange === undefined) { + return undefined; + } + var extractions = getPossibleExtractions(targetRange, context); + if (extractions === undefined) { + return undefined; + } + var actions = []; + var usedNames = ts.createMap(); + var i = 0; + for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { + var extr = extractions_1[_i]; + if (extr.errors && extr.errors.length) { + continue; + } + var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_function_into_0.message, [extr.scopeDescription]); + if (!usedNames.has(description)) { + usedNames.set(description, true); + actions.push({ + description: description, + name: "scope_" + i + }); + } + i++; + } + if (actions.length === 0) { + return undefined; + } + return [{ + name: extractMethod.name, + description: extractMethod.description, + inlineable: true, + actions: actions + }]; + } + function getEditsForAction(context, actionName) { + var length = context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: length }); + var targetRange = rangeToExtract.targetRange; + var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); + ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); + var index = +parsedIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); + var extractions = getPossibleExtractions(targetRange, context, index); + ts.Debug.assert(extractions !== undefined, "The extraction went missing? How?"); + return ({ edits: extractions[0].changes }); + } + var Messages; + (function (Messages) { + function createMessage(message) { + return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; + } + Messages.CannotExtractFunction = createMessage("Cannot extract function."); + Messages.StatementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.CannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.TypeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.InsufficientSelection = createMessage("Select more than a single identifier."); + Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); + Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + })(Messages || (Messages = {})); + var RangeFacts; + (function (RangeFacts) { + RangeFacts[RangeFacts["None"] = 0] = "None"; + RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn"; + RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis"; + RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; + })(RangeFacts = extractMethod_1.RangeFacts || (extractMethod_1.RangeFacts = {})); + function getRangeToExtract(sourceFile, span) { + var length = span.length || 0; + var start = getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, false), sourceFile, span); + var end = getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); + var declarations = []; + var rangeFacts = RangeFacts.None; + if (!start || !end) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractFunction)] }; + } + if (start.parent !== end.parent) { + var startParent = ts.skipParentheses(start.parent); + var endParent = ts.skipParentheses(end.parent); + if (ts.isBinaryExpression(startParent) && ts.isBinaryExpression(endParent) && ts.isNodeDescendantOf(startParent, endParent)) { + start = end = endParent; + } + else { + return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + } + } + if (start !== end) { + if (!isBlockLike(start.parent)) { + return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + } + var statements = []; + for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement === start || statements.length) { + var errors = checkNode(statement); + if (errors) { + return { errors: errors }; + } + statements.push(statement); + } + if (statement === end) { + break; + } + } + return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } 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 errors = checkRootNode(start) || checkNode(start); + if (errors) { + return { errors: errors }; } - var memberDeclaration = symbol.valueDeclaration; - var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - return; + var range = ts.isStatement(start) + ? [start] + : start.parent && start.parent.kind === 210 + ? [start.parent] + : start; + return { targetRange: { range: range, facts: rangeFacts, declarations: declarations } }; + } + function createErrorResult(sourceFile, start, length, message) { + return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; + } + function checkRootNode(node) { + if (ts.isIdentifier(node)) { + return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; } - 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); + return undefined; + } + function checkForStaticContext(nodeToCheck, containingClass) { + var current = nodeToCheck; + while (current !== containingClass) { + if (current.kind === 149) { + if (ts.hasModifier(current, 32)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 146) { + var ctorOrMethod = ts.getContainingFunction(current); + if (ctorOrMethod.kind === 152) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 151) { + if (ts.hasModifier(current, 32)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + } + current = current.parent; } - switch (assignmentBinaryExpression.right.kind) { - case 186: { - var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); - copyComments(assignmentBinaryExpression, method); - return method; + } + function checkNode(nodeToCheck) { + var PermittedJumps; + (function (PermittedJumps) { + PermittedJumps[PermittedJumps["None"] = 0] = "None"; + PermittedJumps[PermittedJumps["Break"] = 1] = "Break"; + PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; + PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + if (!ts.isStatement(nodeToCheck) && !(ts.isExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; + } + if (ts.isInAmbientContext(nodeToCheck)) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.CannotExtractAmbientBlock)]; + } + var containingClass = ts.getContainingClass(nodeToCheck); + if (containingClass) { + checkForStaticContext(nodeToCheck, containingClass); + } + var errors; + var permittedJumps = 4; + var seenLabels; + visit(nodeToCheck); + return errors; + function visit(node) { + if (errors) { + return true; } - case 187: { - var arrowFunction = assignmentBinaryExpression.right; - var arrowFunctionBody = arrowFunction.body; - var bodyBlock = void 0; - if (arrowFunctionBody.kind === 207) { - bodyBlock = arrowFunctionBody; + if (ts.isDeclaration(node)) { + var declaringNode = (node.kind === 226) ? node.parent.parent : node; + if (ts.hasModifier(declaringNode, 1)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + return true; } - else { - var expression = arrowFunctionBody; - bodyBlock = ts.createBlock([ts.createReturn(expression)]); - } - var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); - copyComments(assignmentBinaryExpression, method); - return method; + declarations.push(node.symbol); } - default: { - if (ts.isSourceFileJavaScript(sourceFile)) { - return; - } - var prop = ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); - copyComments(assignmentBinaryExpression.parent, prop); - return prop; + switch (node.kind) { + case 238: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + return true; + case 97: + if (node.parent.kind === 181) { + var containingClass_1 = ts.getContainingClass(node); + if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + return true; + } + } + else { + rangeFacts |= RangeFacts.UsesThis; + } + break; } + if (!node || ts.isFunctionLike(node) || ts.isClassLike(node)) { + switch (node.kind) { + case 228: + case 229: + if (node.parent.kind === 265 && node.parent.externalModuleIndicator === undefined) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.FunctionWillNotBeVisibleInTheNewScope)); + } + break; + } + return false; + } + var savedPermittedJumps = permittedJumps; + if (node.parent) { + switch (node.parent.kind) { + case 211: + if (node.parent.thenStatement === node || node.parent.elseStatement === node) { + permittedJumps = 0; + } + break; + case 224: + if (node.parent.tryBlock === node) { + permittedJumps = 0; + } + else if (node.parent.finallyBlock === node) { + permittedJumps = 4; + } + break; + case 260: + if (node.parent.block === node) { + permittedJumps = 0; + } + break; + case 257: + if (node.expression !== node) { + permittedJumps |= 1; + } + break; + default: + if (ts.isIterationStatement(node.parent, false)) { + if (node.parent.statement === node) { + permittedJumps |= 1 | 2; + } + } + break; + } + } + switch (node.kind) { + case 169: + case 99: + rangeFacts |= RangeFacts.UsesThis; + break; + case 222: + { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } + case 218: + case 217: + { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } + else { + if (!(permittedJumps & (218 ? 1 : 2))) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } + case 191: + rangeFacts |= RangeFacts.IsAsyncFunction; + break; + case 197: + rangeFacts |= RangeFacts.IsGenerator; + break; + case 219: + if (permittedJumps & 4) { + rangeFacts |= RangeFacts.HasReturn; + } + else { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalReturnStatement)); + } + break; + default: + ts.forEachChild(node, visit); + break; + } + permittedJumps = savedPermittedJumps; } } } - function copyComments(sourceNode, targetNode) { - ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { - if (kind === 3) { - pos += 2; - end -= 2; + extractMethod_1.getRangeToExtract = getRangeToExtract; + function isValidExtractionTarget(node) { + return (node.kind === 228) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + } + function collectEnclosingScopes(range) { + var current = isReadonlyArray(range.range) ? ts.firstOrUndefined(range.range) : range.range; + if (range.facts & RangeFacts.UsesThis) { + var containingClass = ts.getContainingClass(current); + if (containingClass) { + return [containingClass]; + } + } + var start = current; + var scopes = undefined; + while (current) { + if (current !== start && isValidExtractionTarget(current)) { + (scopes = scopes || []).push(current); + } + if (current && current.parent && current.parent.kind === 146) { + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLike(parent); }).parent; } else { - pos += 2; + current = current.parent; } - ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + } + return scopes; + } + extractMethod_1.collectEnclosingScopes = collectEnclosingScopes; + function getPossibleExtractions(targetRange, context, requestedChangesIndex) { + if (requestedChangesIndex === void 0) { requestedChangesIndex = undefined; } + var sourceFile = context.file; + if (targetRange === undefined) { + return undefined; + } + var scopes = collectEnclosingScopes(targetRange); + if (scopes === undefined) { + return undefined; + } + var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + var _a = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker()), target = _a.target, usagesPerScope = _a.usagesPerScope, errorsPerScope = _a.errorsPerScope; + context.cancellationToken.throwIfCancellationRequested(); + if (requestedChangesIndex !== undefined) { + if (errorsPerScope[requestedChangesIndex].length) { + return undefined; + } + return [extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context)]; + } + else { + return scopes.map(function (scope, i) { + var errors = errorsPerScope[i]; + if (errors.length) { + return { + scope: scope, + scopeDescription: getDescriptionForScope(scope), + errors: errors + }; + } + return { scope: scope, scopeDescription: getDescriptionForScope(scope) }; + }); + } + } + extractMethod_1.getPossibleExtractions = getPossibleExtractions; + function getDescriptionForScope(scope) { + if (ts.isFunctionLike(scope)) { + switch (scope.kind) { + case 152: + return "constructor"; + case 186: + return scope.name + ? "function expression " + scope.name.getText() + : "anonymous function expression"; + case 228: + return "function " + scope.name.getText(); + case 187: + return "arrow function"; + case 151: + return "method " + scope.name.getText(); + case 153: + return "get " + scope.name.getText(); + case 154: + return "set " + scope.name.getText(); + } + } + else if (ts.isModuleBlock(scope)) { + return "namespace " + scope.parent.name.getText(); + } + else if (ts.isClassLike(scope)) { + return scope.kind === 229 + ? "class " + scope.name.text + : scope.name.text + ? "class expression " + scope.name.text + : "anonymous class expression"; + } + else if (ts.isSourceFile(scope)) { + return "file '" + scope.fileName + "'"; + } + else { + return "unknown"; + } + } + function getUniqueName(isNameOkay) { + var functionNameText = "newFunction"; + if (isNameOkay(functionNameText)) { + return functionNameText; + } + var i = 1; + while (!isNameOkay(functionNameText = "newFunction_" + i)) { + i++; + } + return functionNameText; + } + function extractFunctionInScope(node, scope, _a, range, context) { + var usagesInScope = _a.usages, substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + var file = scope.getSourceFile(); + var functionNameText = getUniqueName(function (n) { return !file.identifiers.has(n); }); + var isJS = ts.isInJavaScriptFile(scope); + var functionName = ts.createIdentifier(functionNameText); + var functionReference = ts.createIdentifier(functionNameText); + var returnType = undefined; + var parameters = []; + var callArguments = []; + var writes; + usagesInScope.forEach(function (usage, name) { + var typeNode = undefined; + if (!isJS) { + var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + type = checker.getBaseTypeOfLiteralType(type); + typeNode = checker.typeToTypeNode(type, node, ts.NodeBuilderFlags.NoTruncation); + } + var paramDecl = ts.createParameter(undefined, undefined, undefined, name, undefined, typeNode); + parameters.push(paramDecl); + if (usage.usage === 2) { + (writes || (writes = [])).push(usage); + } + callArguments.push(ts.createIdentifier(name)); }); + if (ts.isExpression(node) && !isJS) { + var contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType); + } + var _b = transformFunctionBody(node), body = _b.body, returnValueProperty = _b.returnValueProperty; + var newFunction; + if (ts.isClassLike(scope)) { + var modifiers = isJS ? [] : [ts.createToken(112)]; + if (range.facts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(115)); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + modifiers.push(ts.createToken(120)); + } + newFunction = ts.createMethod(undefined, modifiers, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, undefined, [], parameters, returnType, body); + } + else { + newFunction = ts.createFunctionDeclaration(undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, [], parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + var newNodes = []; + var call = ts.createCall(ts.isClassLike(scope) ? ts.createPropertyAccess(range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.getText()) : ts.createThis(), functionReference) : functionReference, undefined, callArguments); + if (range.facts & RangeFacts.IsGenerator) { + call = ts.createYield(ts.createToken(39), call); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + call = ts.createAwait(call); + } + if (writes) { + if (returnValueProperty) { + newNodes.push(ts.createVariableStatement(undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119))])); + } + var assignments = getPropertyAssignmentsForWrites(writes); + if (returnValueProperty) { + assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); + } + if (assignments.length === 1) { + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + else { + newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58, call))); + } + } + else { + newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58, call))); + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + } + } + else { + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn(call)); + } + else if (isReadonlyArray(range.range)) { + newNodes.push(ts.createStatement(call)); + } + else { + newNodes.push(call); + } + } + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { + nodeSeparator: context.newLineCharacter, + suffix: context.newLineCharacter + }); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); + } + return { + scope: scope, + scopeDescription: getDescriptionForScope(scope), + changes: changeTracker.getChanges() + }; + function getPropertyAssignmentsForWrites(writes) { + return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + } + function generateReturnValueProperty() { + return "__return"; + } + function transformFunctionBody(body) { + if (ts.isBlock(body) && !writes && substitutions.size === 0) { + return { body: ts.createBlock(body.statements, true), returnValueProperty: undefined }; + } + var returnValueProperty; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + if (writes || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (writes && !(range.facts & RangeFacts.HasReturn) && ts.isStatement(body)) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, true), returnValueProperty: undefined }; + } + function visitor(node) { + if (node.kind === 219 && writes) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = generateReturnValueProperty(); + } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); + } + else { + return ts.createReturn(ts.createObjectLiteral(assignments)); + } + } + else { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } + } } - function createClassFromVariableDeclaration(node) { - var initializer = node.initializer; - if (!initializer || initializer.kind !== 186) { + extractMethod_1.extractFunctionInScope = extractFunctionInScope; + function isReadonlyArray(v) { + return ts.isArray(v); + } + function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) + ? { pos: targetRange.range[0].getStart(sourceFile), end: targetRange.range[targetRange.range.length - 1].getEnd() } + : targetRange.range; + } + var Usage; + (function (Usage) { + Usage[Usage["Read"] = 1] = "Read"; + Usage[Usage["Write"] = 2] = "Write"; + })(Usage || (Usage = {})); + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker) { + var usagesPerScope = []; + var substitutionsPerScope = []; + var errorsPerScope = []; + var visibleDeclarationsInExtractedRange = []; + for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { + var _ = scopes_1[_i]; + usagesPerScope.push({ usages: ts.createMap(), substitutions: ts.createMap() }); + substitutionsPerScope.push(ts.createMap()); + errorsPerScope.push([]); + } + var seenUsages = ts.createMap(); + var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); + collectUsages(target); + var _loop_8 = function (i) { + var hasWrite = false; + var readonlyClassPropertyWrite = undefined; + usagesPerScope[i].usages.forEach(function (value) { + if (value.usage === 2) { + hasWrite = true; + if (value.symbol.flags & 106500 && + value.symbol.valueDeclaration && + ts.hasModifier(value.symbol.valueDeclaration, 64)) { + readonlyClassPropertyWrite = value.symbol.valueDeclaration; + } + } + }); + if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { + errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); + } + else if (readonlyClassPropertyWrite && i > 0) { + errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotCombineWritesAndReturns)); + } + }; + for (var i = 0; i < scopes.length; i++) { + _loop_8(i); + } + if (visibleDeclarationsInExtractedRange.length) { + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + function collectUsages(node, valueUsage) { + if (valueUsage === void 0) { valueUsage = 1; } + if (ts.isDeclaration(node) && node.symbol) { + visibleDeclarationsInExtractedRange.push(node.symbol); + } + if (ts.isAssignmentExpression(node)) { + collectUsages(node.left, 2); + collectUsages(node.right); + } + else if (ts.isUnaryExpressionWithWrite(node)) { + collectUsages(node.operand, 2); + } + else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { + ts.forEachChild(node, collectUsages); + } + else if (ts.isIdentifier(node)) { + if (!node.parent) { + return; + } + if (ts.isQualifiedName(node.parent) && node !== node.parent.left) { + return; + } + if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { + return; + } + recordUsage(node, valueUsage, ts.isPartOfTypeNode(node)); + } + else { + ts.forEachChild(node, collectUsages); + } + } + function recordUsage(n, usage, isTypeNode) { + var symbolId = recordUsagebySymbol(n, usage, isTypeNode); + if (symbolId) { + for (var i = 0; i < scopes.length; i++) { + var substitition = substitutionsPerScope[i].get(symbolId); + if (substitition) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitition); + } + } + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + var symbol = checker.getSymbolAtLocation(identifier); + if (!symbol) { + return undefined; + } + var symbolId = ts.getSymbolId(symbol).toString(); + var lastUsage = seenUsages.get(symbolId); + if (lastUsage && lastUsage >= usage) { + return symbolId; + } + seenUsages.set(symbolId, usage); + if (lastUsage) { + for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) { + var perScope = usagesPerScope_1[_i]; + var prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) { + perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + return symbolId; + } + var declInFile = ts.find(symbol.getDeclarations(), function (d) { return d.getSourceFile() === sourceFile; }); + if (!declInFile) { + return undefined; + } + if (ts.rangeContainsRange(enclosingTextRange, declInFile)) { + return undefined; + } + if (targetRange.facts & RangeFacts.IsGenerator && usage === 2) { + for (var _a = 0, errorsPerScope_1 = errorsPerScope; _a < errorsPerScope_1.length; _a++) { + var errors = errorsPerScope_1[_a]; + errors.push(ts.createDiagnosticForNode(identifier, Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators)); + } + } + for (var i = 0; i < scopes.length; i++) { + var scope = scopes[i]; + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + if (resolvedSymbol === symbol) { + continue; + } + if (!substitutionsPerScope[i].has(symbolId)) { + var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) { + substitutionsPerScope[i].set(symbolId, substitution); + } + else if (isTypeName) { + errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + } + else { + usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + } + return symbolId; + } + function checkForUsedDeclarations(node) { + if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) { + return; + } + var sym = checker.getSymbolAtLocation(node); + if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { + for (var _i = 0, errorsPerScope_2 = errorsPerScope; _i < errorsPerScope_2.length; _i++) { + var scope = errorsPerScope_2[_i]; + scope.push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + } + return true; + } + else { + ts.forEachChild(node, checkForUsedDeclarations); + } + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { + if (!symbol) { + return undefined; + } + if (symbol.getDeclarations().some(function (d) { return d.parent === scopeDecl; })) { + return ts.createIdentifier(symbol.name); + } + var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); + if (prefix === undefined) { + return undefined; + } + return isTypeNode ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) : ts.createPropertyAccess(prefix, symbol.name); + } + } + function getParentNodeInSpan(node, file, span) { + if (!node) return undefined; + while (node.parent) { + if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) { + return node; + } + node = node.parent; } - 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)); - } - var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); - return cls; } - function createClassFromFunctionDeclaration(node) { - var memberElements = createClassElementsFromSymbol(ctorSymbol); - if (node.body) { - memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); - } - var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); - return cls; + function spanContainsNode(span, node, file) { + return ts.textSpanContainsPosition(span, node.getStart(file)) && + node.getEnd() <= ts.textSpanEnd(span); } - } + function isExtractableExpression(node) { + switch (node.parent.kind) { + case 264: + return false; + } + switch (node.kind) { + case 9: + return node.parent.kind !== 238 && + node.parent.kind !== 242; + case 198: + case 174: + case 176: + return false; + case 71: + return node.parent.kind !== 176 && + node.parent.kind !== 242 && + node.parent.kind !== 246; + } + return true; + } + function isBlockLike(node) { + switch (node.kind) { + case 207: + case 265: + case 234: + case 257: + return true; + default: + return false; + } + } + })(extractMethod = refactor.extractMethod || (refactor.extractMethod = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); var ts; @@ -74186,12 +75614,14 @@ var ts; ts.scanner.setTextPos(pos); while (pos < end) { var token = ts.scanner.scan(); - ts.Debug.assert(token !== 1); var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); } pos = textPos; + if (token === 1) { + break; + } } return pos; }; @@ -74986,8 +76416,8 @@ var ts; if (program) { var oldSourceFiles = program.getSourceFiles(); var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); } @@ -75009,7 +76439,7 @@ var ts; if (!shouldCreateNewSourceFiles) { var oldSourceFile = program && program.getSourceFileByPath(path); if (oldSourceFile) { - ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + path); + ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path); return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } } @@ -75372,17 +76802,19 @@ var ts; function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var settings = toEditorSettings(options); - if (key === "{") { - return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + if (!ts.isInComment(sourceFile, position)) { + if (key === "{") { + return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "}") { + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === ";") { + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "\n") { + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + } } return []; } @@ -75422,6 +76854,11 @@ var ts; } return true; } + function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine); + return range && ts.createTextSpanFromRange(range); + } function getTodoComments(fileName, descriptors) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -75545,6 +76982,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, @@ -75615,12 +77053,16 @@ var ts; function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(node.name)); - if (name && contextualType) { + return getPropertySymbolsFromType(contextualType, node.name); + } + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + function getPropertySymbolsFromType(type, propName) { + var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); + if (name && type) { var result_10 = []; - var symbol = contextualType.getProperty(name); - if (contextualType.flags & 65536) { - ts.forEach(contextualType.types, function (t) { + var symbol = type.getProperty(name); + if (type.flags & 65536) { + ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { result_10.push(symbol); @@ -75635,7 +77077,7 @@ var ts; } return undefined; } - ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + ts.getPropertySymbolsFromType = getPropertySymbolsFromType; function isArgumentOfElementAccessExpression(node) { return node && node.parent && @@ -75666,6 +77108,7 @@ var ts; Arguments.LogFile = "--logFile"; Arguments.EnableTelemetry = "--enableTelemetry"; Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.TypesMapLocation = "--typesMapLocation"; Arguments.NpmLocation = "--npmLocation"; })(Arguments = server.Arguments || (server.Arguments = {})); function hasArgument(argumentName) { @@ -75713,7 +77156,7 @@ var ts; function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), - fileNames: project.getFileNames(true, true), + fileNames: project.getFileNames(true, true).concat(project.getExcludedFiles()), compilerOptions: project.getCompilerOptions(), typeAcquisition: typeAcquisition, unresolvedImports: unresolvedImports, @@ -75813,42 +77256,6 @@ var ts; return []; } server.createSortedArray = createSortedArray; - function toSortedArray(arr, comparer) { - arr.sort(comparer); - return arr; - } - server.toSortedArray = toSortedArray; - function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, compare) { - compare = compare || ts.compareValues; - var newIndex = 0; - var oldIndex = 0; - var newLen = newItems.length; - var oldLen = oldItems.length; - while (newIndex < newLen && oldIndex < oldLen) { - var newItem = newItems[newIndex]; - var oldItem = oldItems[oldIndex]; - var compareResult = compare(newItem, oldItem); - if (compareResult === -1) { - inserted(newItem); - newIndex++; - } - else if (compareResult === 1) { - deleted(oldItem); - oldIndex++; - } - else { - newIndex++; - oldIndex++; - } - } - while (newIndex < newLen) { - inserted(newItems[newIndex++]); - } - while (oldIndex < oldLen) { - deleted(oldItems[oldIndex++]); - } - } - server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; var ThrottledOperations = (function () { function ThrottledOperations(host) { this.host = host; @@ -75893,6 +77300,11 @@ var ts; return GcTimer; }()); server.GcTimer = GcTimer; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +(function (ts) { + var server; + (function (server) { function insertSorted(array, insert, compare) { if (array.length === 0) { array.push(insert); @@ -75918,6 +77330,51 @@ var ts; } } server.removeSorted = removeSorted; + function toSortedArray(arr, comparer) { + arr.sort(comparer); + return arr; + } + server.toSortedArray = toSortedArray; + function toDeduplicatedSortedArray(arr) { + arr.sort(); + ts.filterMutate(arr, isNonDuplicateInSortedArray); + return arr; + } + server.toDeduplicatedSortedArray = toDeduplicatedSortedArray; + function isNonDuplicateInSortedArray(value, index, array) { + return index === 0 || value !== array[index - 1]; + } + function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, compare) { + compare = compare || ts.compareValues; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = compare(newItem, oldItem); + if (compareResult === -1) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1) { + deleted(oldItem); + oldIndex++; + } + else { + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -75931,6 +77388,7 @@ var ts; CommandTypes["Brace"] = "brace"; CommandTypes["BraceFull"] = "brace-full"; CommandTypes["BraceCompletion"] = "braceCompletion"; + CommandTypes["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment"; CommandTypes["Change"] = "change"; CommandTypes["Close"] = "close"; CommandTypes["Completions"] = "completions"; @@ -76022,6 +77480,7 @@ var ts; ModuleKind["System"] = "System"; ModuleKind["ES6"] = "ES6"; ModuleKind["ES2015"] = "ES2015"; + ModuleKind["ESNext"] = "ESNext"; })(ModuleKind = protocol.ModuleKind || (protocol.ModuleKind = {})); var ModuleResolutionKind; (function (ModuleResolutionKind) { @@ -76039,6 +77498,9 @@ var ts; ScriptTarget["ES5"] = "ES5"; ScriptTarget["ES6"] = "ES6"; ScriptTarget["ES2015"] = "ES2015"; + ScriptTarget["ES2016"] = "ES2016"; + ScriptTarget["ES2017"] = "ES2017"; + ScriptTarget["ESNext"] = "ESNext"; })(ScriptTarget = protocol.ScriptTarget || (protocol.ScriptTarget = {})); })(protocol = server.protocol || (server.protocol = {})); })(server = ts.server || (ts.server = {})); @@ -76130,20 +77592,16 @@ var ts; var MultistepOperation = (function () { function MultistepOperation(operationHost) { this.operationHost = operationHost; - this.completed = true; } MultistepOperation.prototype.startNew = function (action) { this.complete(); this.requestId = this.operationHost.getCurrentRequestId(); - this.completed = false; this.executeAction(action); }; MultistepOperation.prototype.complete = function () { - if (!this.completed) { - if (this.requestId) { - this.operationHost.sendRequestCompletedEvent(this.requestId); - } - this.completed = true; + if (this.requestId !== undefined) { + this.operationHost.sendRequestCompletedEvent(this.requestId); + this.requestId = undefined; } this.setTimerHandle(undefined); this.setImmediateId(undefined); @@ -76308,6 +77766,9 @@ var ts; _a[server.CommandNames.DocCommentTemplate] = function (request) { return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); }, + _a[server.CommandNames.GetSpanOfEnclosingComment] = function (request) { + return _this.requiredResponse(_this.getSpanOfEnclosingComment(request.arguments)); + }, _a[server.CommandNames.Format] = function (request) { return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); }, @@ -76479,6 +77940,7 @@ var ts; logger: this.logger, cancellationToken: this.cancellationToken, useSingleInferredProject: opts.useSingleInferredProject, + useInferredProjectPerProjectRoot: opts.useInferredProjectPerProjectRoot, typingsInstaller: this.typingsInstaller, throttleWaitMilliseconds: throttleWaitMilliseconds, eventHandler: this.eventHandler, @@ -76505,7 +77967,7 @@ var ts; case server.ContextEvent: var _a = event.data, project_1 = _a.project, fileName_2 = _a.fileName; this.projectService.logger.info("got context event, updating diagnostics for " + fileName_2); - this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, [{ fileName: fileName_2, project: project_1 }], _this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); }); + this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, [{ fileName: fileName_2, project: project_1 }], 100); }); break; case server.ConfigFileDiagEvent: var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; @@ -76613,26 +78075,24 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) { + Session.prototype.updateProjectStructure = function () { var _this = this; - if (ms === void 0) { ms = 1500; } + var ms = 1500; + var seq = this.changeSeq; this.host.setTimeout(function () { - if (matchSeq(seq)) { + if (_this.changeSeq === seq) { _this.projectService.refreshInferredProjects(); } }, ms); }; - Session.prototype.updateErrorCheck = function (next, checkList, seq, matchSeq, ms, followMs, requireOpen) { + Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) { var _this = this; - if (ms === void 0) { ms = 1500; } - if (followMs === void 0) { followMs = 200; } if (requireOpen === void 0) { requireOpen = true; } - if (followMs > ms) { - followMs = ms; - } + var seq = this.changeSeq; + var followMs = Math.min(ms, 200); var index = 0; var checkOne = function () { - if (matchSeq(seq)) { + if (_this.changeSeq === seq) { var checkSpec_1 = checkList[index]; index++; if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { @@ -76646,7 +78106,7 @@ var ts; } } }; - if ((checkList.length > index) && (matchSeq(seq))) { + if (checkList.length > index && this.changeSeq === seq) { next.delay(ms, checkOne); } }; @@ -76724,7 +78184,7 @@ var ts; Session.prototype.getDiagnosticsWorker = function (args, isSemantic, selector, includeLinePosition) { var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { - return []; + return server.emptyArray; } var scriptInfo = project.getScriptInfoForNormalizedPath(file); var diagnostics = selector(project, file); @@ -76738,7 +78198,7 @@ var ts; var position = this.getPosition(args, scriptInfo); var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); if (!definitions) { - return undefined; + return server.emptyArray; } if (simplifiedResult) { return definitions.map(function (def) { @@ -76760,7 +78220,7 @@ var ts; var position = this.getPosition(args, scriptInfo); var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); if (!definitions) { - return undefined; + return server.emptyArray; } return definitions.map(function (def) { var defScriptInfo = project.getScriptInfo(def.fileName); @@ -76776,7 +78236,7 @@ var ts; var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); var implementations = project.getLanguageService().getImplementationAtPosition(file, position); if (!implementations) { - return []; + return server.emptyArray; } if (simplifiedResult) { return implementations.map(function (_a) { @@ -76799,7 +78259,7 @@ var ts; var position = this.getPosition(args, scriptInfo); var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); if (!occurrences) { - return undefined; + return server.emptyArray; } return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan, isInString = occurrence.isInString; @@ -76821,7 +78281,7 @@ var ts; Session.prototype.getSyntacticDiagnosticsSync = function (args) { var configFile = this.getConfigFileAndProject(args).configFile; if (configFile) { - return []; + return server.emptyArray; } return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); }; @@ -76838,7 +78298,7 @@ var ts; var position = this.getPosition(args, scriptInfo); var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); if (!documentHighlights) { - return undefined; + return server.emptyArray; } if (simplifiedResult) { return documentHighlights.map(convertToDocumentHighlightsItem); @@ -76862,7 +78322,7 @@ var ts; } }; Session.prototype.setCompilerOptionsForInferredProjects = function (args) { - this.projectService.setCompilerOptionsForInferredProjects(args.options); + this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); }; Session.prototype.getProjectInfo = function (args) { return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, false); @@ -76924,13 +78384,13 @@ var ts; if (!renameInfo.canRename) { return { info: renameInfo, - locs: [] + locs: server.emptyArray }; } var fileSpans = server.combineProjectOutput(projects, function (project) { var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); if (!renameLocations) { - return []; + return server.emptyArray; } return renameLocations.map(function (location) { var locationScriptInfo = project.getScriptInfo(location.fileName); @@ -77011,7 +78471,7 @@ var ts; var refs = server.combineProjectOutput(projects, function (project) { var references = project.getLanguageService().getReferencesAtPosition(file, position); if (!references) { - return []; + return server.emptyArray; } return references.map(function (ref) { var refScriptInfo = project.getScriptInfo(ref.fileName); @@ -77052,7 +78512,7 @@ var ts; if (this.eventHandler) { this.eventHandler({ eventName: "configFileDiag", - data: { triggerFile: fileName, configFileName: configFileName, diagnostics: configFileErrors || [] } + data: { triggerFile: fileName, configFileName: configFileName, diagnostics: configFileErrors || server.emptyArray } }); } }; @@ -77089,6 +78549,13 @@ var ts; var position = this.getPosition(args, scriptInfo); return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); }; + Session.prototype.getSpanOfEnclosingComment = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var onlyMultiLine = args.onlyMultiLine; + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService(false).getSpanOfEnclosingComment(file, position, onlyMultiLine); + }; Session.prototype.getIndentation = function (args) { var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); @@ -77212,15 +78679,12 @@ var ts; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); var completions = project.getLanguageService().getCompletionsAtPosition(file, position); - if (!completions) { - return undefined; - } if (simplifiedResult) { - return ts.mapDefined(completions.entries, function (entry) { + return ts.mapDefined(completions && completions.entries, function (entry) { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; + var name_68 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; - return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }; + return { name: name_68, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }; } }).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); } @@ -77240,7 +78704,7 @@ var ts; var info = this.projectService.getScriptInfo(args.file); var result = []; if (!info) { - return []; + return server.emptyArray; } var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { @@ -77300,11 +78764,10 @@ var ts; return project && { fileName: fileName, project: project }; }); if (checkList.length > 0) { - this.updateErrorCheck(next, checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); + this.updateErrorCheck(next, checkList, delay); } }; Session.prototype.change = function (args) { - var _this = this; var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; if (project) { var scriptInfo = project.getScriptInfoForNormalizedPath(file); @@ -77314,7 +78777,7 @@ var ts; scriptInfo.editContent(start, end, args.insertString); this.changeSeq++; } - this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; }); + this.updateProjectStructure(); } }; Session.prototype.reload = function (args, reqSeq) { @@ -77393,7 +78856,7 @@ var ts; return server.combineProjectOutput(projects, function (project) { var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); if (!navItems) { - return []; + return server.emptyArray; } return navItems.map(function (navItem) { var scriptInfo = project.getScriptInfo(navItem.fileName); @@ -77492,13 +78955,13 @@ var ts; } if (simplifiedResult) { var file_2 = result.renameFilename; - var location = void 0; + var location_4; if (file_2 !== undefined && result.renameLocation !== undefined) { var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(file_2)); - location = renameScriptInfo.positionToLineOffset(result.renameLocation); + location_4 = renameScriptInfo.positionToLineOffset(result.renameLocation); } return { - renameLocation: location, + renameLocation: location_4, renameFilename: file_2, edits: result.edits.map(function (change) { return _this.mapTextChangesToCodeEdits(project, change); }) }; @@ -77583,7 +79046,6 @@ var ts; : spans; }; Session.prototype.getDiagnosticsForProject = function (next, delay, fileName) { - var _this = this; var _a = this.getProjectInfoWorker(fileName, undefined, true, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; @@ -77618,7 +79080,7 @@ var ts; fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); - this.updateErrorCheck(next, checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay, 200, false); + this.updateErrorCheck(next, checkList, delay, false); } }; Session.prototype.getCanonicalFileName = function (fileName) { @@ -77725,13 +79187,13 @@ var ts; CharRangeSection[CharRangeSection["Mid"] = 3] = "Mid"; CharRangeSection[CharRangeSection["End"] = 4] = "End"; CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd"; - })(CharRangeSection = server.CharRangeSection || (server.CharRangeSection = {})); + })(CharRangeSection || (CharRangeSection = {})); var EditWalker = (function () { function EditWalker() { this.goSubtree = true; this.lineIndex = new LineIndex(); this.endBranch = []; - this.state = CharRangeSection.Entire; + this.state = 2; this.initialText = ""; this.trailingText = ""; this.lineIndex.root = new LineNode(); @@ -77820,14 +79282,14 @@ var ts; }; EditWalker.prototype.post = function (_relativeStart, _relativeLength, lineCollection) { if (lineCollection === this.lineCollectionAtBranch) { - this.state = CharRangeSection.End; + this.state = 4; } this.stack.pop(); }; EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { var currentNode = this.stack[this.stack.length - 1]; - if ((this.state === CharRangeSection.Entire) && (nodeType === CharRangeSection.Start)) { - this.state = CharRangeSection.Start; + if ((this.state === 2) && (nodeType === 1)) { + this.state = 1; this.branchNode = currentNode; this.lineCollectionAtBranch = lineCollection; } @@ -77840,14 +79302,14 @@ var ts; return new LineNode(); } switch (nodeType) { - case CharRangeSection.PreStart: + case 0: this.goSubtree = false; - if (this.state !== CharRangeSection.End) { + if (this.state !== 4) { currentNode.add(lineCollection); } break; - case CharRangeSection.Start: - if (this.state === CharRangeSection.End) { + case 1: + if (this.state === 4) { this.goSubtree = false; } else { @@ -77856,8 +79318,8 @@ var ts; this.startPath.push(child); } break; - case CharRangeSection.Entire: - if (this.state !== CharRangeSection.End) { + case 2: + if (this.state !== 4) { child = fresh(lineCollection); currentNode.add(child); this.startPath.push(child); @@ -77870,11 +79332,11 @@ var ts; } } break; - case CharRangeSection.Mid: + case 3: this.goSubtree = false; break; - case CharRangeSection.End: - if (this.state !== CharRangeSection.End) { + case 4: + if (this.state !== 4) { this.goSubtree = false; } else { @@ -77885,9 +79347,9 @@ var ts; } } break; - case CharRangeSection.PostEnd: + case 5: this.goSubtree = false; - if (this.state !== CharRangeSection.Start) { + if (this.state !== 1) { currentNode.add(lineCollection); } break; @@ -77897,10 +79359,10 @@ var ts; } }; EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) { - if (this.state === CharRangeSection.Start) { + if (this.state === 1) { this.initialText = ll.text.substring(0, relativeStart); } - else if (this.state === CharRangeSection.Entire) { + else if (this.state === 2) { this.initialText = ll.text.substring(0, relativeStart); this.trailingText = ll.text.substring(relativeStart + relativeLength); } @@ -77921,7 +79383,6 @@ var ts; }; return TextChange; }()); - server.TextChange = TextChange; var ScriptVersionCache = (function () { function ScriptVersionCache() { this.changes = []; @@ -77946,15 +79407,6 @@ var ts; this.getSnapshot(); } }; - ScriptVersionCache.prototype.latest = function () { - return this.versions[this.currentVersionToIndex()]; - }; - ScriptVersionCache.prototype.latestVersion = function () { - if (this.changes.length > 0) { - this.getSnapshot(); - } - return this.currentVersion; - }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; @@ -77967,7 +79419,8 @@ var ts; snap.index.load(lm.lines); this.minVersion = this.currentVersion; }; - ScriptVersionCache.prototype.getSnapshot = function () { + ScriptVersionCache.prototype.getSnapshot = function () { return this._getSnapshot(); }; + ScriptVersionCache.prototype._getSnapshot = function () { var snap = this.versions[this.currentVersionToIndex()]; if (this.changes.length > 0) { var snapIndex = snap.index; @@ -77985,6 +79438,24 @@ var ts; } return snap; }; + ScriptVersionCache.prototype.getSnapshotVersion = function () { + return this._getSnapshot().version; + }; + ScriptVersionCache.prototype.getLineInfo = function (line) { + return this._getSnapshot().index.lineNumberToInfo(line); + }; + ScriptVersionCache.prototype.lineOffsetToPosition = function (line, column) { + return this._getSnapshot().index.absolutePositionOfStartOfLine(line) + (column - 1); + }; + ScriptVersionCache.prototype.positionToLineOffset = function (position) { + return this._getSnapshot().index.positionToLineOffset(position); + }; + ScriptVersionCache.prototype.lineToTextSpan = function (line) { + var index = this._getSnapshot().index; + var _a = index.lineNumberToInfo(line + 1), lineText = _a.lineText, absolutePosition = _a.absolutePosition; + var len = lineText !== undefined ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition; + return ts.createTextSpan(absolutePosition, len); + }; ScriptVersionCache.prototype.getTextChangesBetweenVersions = function (oldVersion, newVersion) { if (oldVersion < newVersion) { if (oldVersion >= this.minVersion) { @@ -78046,7 +79517,6 @@ var ts; }; return LineIndexSnapshot; }()); - server.LineIndexSnapshot = LineIndexSnapshot; var LineIndex = (function () { function LineIndex() { this.checkEdits = false; @@ -78245,18 +79715,18 @@ var ts; var childCharCount = this.children[childIndex].charCount(); var adjustedStart = rangeStart; while (adjustedStart >= childCharCount) { - this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, CharRangeSection.PreStart); + this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0); adjustedStart -= childCharCount; childIndex++; childCharCount = this.children[childIndex].charCount(); } if ((adjustedStart + rangeLength) <= childCharCount) { - if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, CharRangeSection.Entire)) { + if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2)) { return; } } else { - if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, CharRangeSection.Start)) { + if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1)) { return; } var adjustedLength = rangeLength - (childCharCount - adjustedStart); @@ -78264,7 +79734,7 @@ var ts; var child = this.children[childIndex]; childCharCount = child.charCount(); while (adjustedLength > childCharCount) { - if (this.execWalk(0, childCharCount, walkFns, childIndex, CharRangeSection.Mid)) { + if (this.execWalk(0, childCharCount, walkFns, childIndex, 3)) { return; } adjustedLength -= childCharCount; @@ -78272,7 +79742,7 @@ var ts; childCharCount = this.children[childIndex].charCount(); } if (adjustedLength > 0) { - if (this.execWalk(0, adjustedLength, walkFns, childIndex, CharRangeSection.End)) { + if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4)) { return; } } @@ -78281,82 +79751,46 @@ var ts; var clen = this.children.length; if (childIndex < (clen - 1)) { for (var ej = childIndex + 1; ej < clen; ej++) { - this.skipChild(0, 0, ej, walkFns, CharRangeSection.PostEnd); + this.skipChild(0, 0, ej, walkFns, 5); } } } }; LineNode.prototype.charOffsetToLineInfo = function (lineNumberAccumulator, relativePosition) { - var childInfo = this.childFromCharOffset(lineNumberAccumulator, relativePosition); - if (!childInfo.child) { - return { - oneBasedLine: lineNumberAccumulator, - zeroBasedColumn: relativePosition, - lineText: undefined, - }; + if (this.children.length === 0) { + return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: undefined }; } - else if (childInfo.childIndex < this.children.length) { - if (childInfo.child.isLeaf()) { - return { - oneBasedLine: childInfo.lineNumberAccumulator, - zeroBasedColumn: childInfo.relativePosition, - lineText: childInfo.child.text, - }; - } - else { - var lineNode = (childInfo.child); - return lineNode.charOffsetToLineInfo(childInfo.lineNumberAccumulator, childInfo.relativePosition); - } - } - else { - var lineInfo = this.lineNumberToInfo(this.lineCount(), 0); - return { oneBasedLine: this.lineCount(), zeroBasedColumn: lineInfo.leaf.charCount(), lineText: undefined }; - } - }; - LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) { - var childInfo = this.childFromLineNumber(relativeOneBasedLine, positionAccumulator); - if (!childInfo.child) { - return { position: positionAccumulator, leaf: undefined }; - } - else if (childInfo.child.isLeaf()) { - return { position: childInfo.positionAccumulator, leaf: childInfo.child }; - } - else { - var lineNode = (childInfo.child); - return lineNode.lineNumberToInfo(childInfo.relativeOneBasedLine, childInfo.positionAccumulator); - } - }; - LineNode.prototype.childFromLineNumber = function (relativeOneBasedLine, positionAccumulator) { - var child; - var i; - for (i = 0; i < this.children.length; i++) { - child = this.children[i]; - var childLineCount = child.lineCount(); - if (childLineCount >= relativeOneBasedLine) { - break; - } - else { - relativeOneBasedLine -= childLineCount; - positionAccumulator += child.charCount(); - } - } - return { child: child, relativeOneBasedLine: relativeOneBasedLine, positionAccumulator: positionAccumulator }; - }; - LineNode.prototype.childFromCharOffset = function (lineNumberAccumulator, relativePosition) { - var child; - var i; - var len; - for (i = 0, len = this.children.length; i < len; i++) { - child = this.children[i]; + for (var _i = 0, _a = this.children; _i < _a.length; _i++) { + var child = _a[_i]; if (child.charCount() > relativePosition) { - break; + if (child.isLeaf()) { + return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: child.text }; + } + else { + return child.charOffsetToLineInfo(lineNumberAccumulator, relativePosition); + } } else { relativePosition -= child.charCount(); lineNumberAccumulator += child.lineCount(); } } - return { child: child, childIndex: i, relativePosition: relativePosition, lineNumberAccumulator: lineNumberAccumulator }; + var leaf = this.lineNumberToInfo(this.lineCount(), 0).leaf; + return { oneBasedLine: this.lineCount(), zeroBasedColumn: leaf.charCount(), lineText: undefined }; + }; + LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) { + for (var _i = 0, _a = this.children; _i < _a.length; _i++) { + var child = _a[_i]; + var childLineCount = child.lineCount(); + if (childLineCount >= relativeOneBasedLine) { + return child.isLeaf() ? { position: positionAccumulator, leaf: child } : child.lineNumberToInfo(relativeOneBasedLine, positionAccumulator); + } + else { + relativeOneBasedLine -= childLineCount; + positionAccumulator += child.charCount(); + } + } + return { position: positionAccumulator, leaf: undefined }; }; LineNode.prototype.splitAfter = function (childIndex) { var splitNode; @@ -78453,7 +79887,6 @@ var ts; }; return LineNode; }()); - server.LineNode = LineNode; var LineLeaf = (function () { function LineLeaf(text) { this.text = text; @@ -78472,7 +79905,6 @@ var ts; }; return LineLeaf; }()); - server.LineLeaf = LineLeaf; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -78488,7 +79920,7 @@ var ts; } TextStorage.prototype.getVersion = function () { return this.svc - ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshot().version + ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshotVersion() : "Text-" + this.textVersion; }; TextStorage.prototype.hasScriptVersionCache = function () { @@ -78526,7 +79958,7 @@ var ts; : ts.ScriptSnapshot.fromString(this.getOrLoadText()); }; TextStorage.prototype.getLineInfo = function (line) { - return this.switchToScriptVersionCache().getSnapshot().index.lineNumberToInfo(line); + return this.switchToScriptVersionCache().getLineInfo(line); }; TextStorage.prototype.lineToTextSpan = function (line) { if (!this.svc) { @@ -78535,23 +79967,20 @@ var ts; var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; return ts.createTextSpanFromBounds(start, end); } - var index = this.svc.getSnapshot().index; - var _a = index.lineNumberToInfo(line + 1), lineText = _a.lineText, absolutePosition = _a.absolutePosition; - var len = lineText !== undefined ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition; - return ts.createTextSpan(absolutePosition, len); + return this.svc.lineToTextSpan(line); }; TextStorage.prototype.lineOffsetToPosition = function (line, offset) { if (!this.svc) { return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); } - return this.svc.getSnapshot().index.absolutePositionOfStartOfLine(line) + (offset - 1); + return this.svc.lineOffsetToPosition(line, offset); }; TextStorage.prototype.positionToLineOffset = function (position) { if (!this.svc) { var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; return { line: line + 1, offset: character + 1 }; } - return this.svc.getSnapshot().index.positionToLineOffset(position); + return this.svc.positionToLineOffset(position); }; TextStorage.prototype.getFileText = function (tempFileName) { return this.host.readFile(tempFileName || this.fileName) || ""; @@ -78817,16 +80246,16 @@ var ts; var compilerOptions = this.getCompilationSettings(); var lastDeletedFileName = this.project.projectService.lastDeletedFile && this.project.projectService.lastDeletedFile.fileName; for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name = names_2[_i]; - var resolution = newResolutions.get(name); + var name_69 = names_2[_i]; + var resolution = newResolutions.get(name_69); if (!resolution) { - var existingResolution = currentResolutionsInFile && currentResolutionsInFile.get(name); + var existingResolution = currentResolutionsInFile && currentResolutionsInFile.get(name_69); if (moduleResolutionIsValid(existingResolution)) { resolution = existingResolution; } else { - resolution = loader(name, containingFile, compilerOptions, this); - newResolutions.set(name, resolution); + resolution = loader(name_69, containingFile, compilerOptions, this); + newResolutions.set(name_69, resolution); } if (logChanges && this.filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { this.filesWithChangedSetOfUnresolvedImports.push(path); @@ -79460,7 +80889,8 @@ var ts; log("Loading " + moduleName + " from " + initialDir + " (resolved to " + resolvedPath + ")"); var result = host.require(resolvedPath, moduleName); if (result.error) { - log("Failed to load module: " + JSON.stringify(result.error)); + var err = result.error.stack || result.error.message || JSON.stringify(result.error); + log("Failed to load module '" + moduleName + "': " + err); return undefined; } return result.module; @@ -79590,7 +81020,7 @@ var ts; return ts.map(this.program.getSourceFiles(), function (sourceFile) { var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); if (!scriptInfo) { - ts.Debug.assert(false, "scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' is missing."); } return scriptInfo; }); @@ -79601,6 +81031,9 @@ var ts; } return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); }; + Project.prototype.getExcludedFiles = function () { + return server.emptyArray; + }; Project.prototype.getFileNames = function (excludeFilesFromExternalLibraries, excludeConfigFiles) { if (!this.program) { return []; @@ -79752,7 +81185,7 @@ var ts; var sourceFile = _b[_a]; this.extractUnresolvedImportsFromSourceFile(sourceFile, result); } - this.lastCachedUnresolvedImportsList = server.toSortedArray(result); + this.lastCachedUnresolvedImportsList = server.toDeduplicatedSortedArray(result); } unresolvedImports = this.lastCachedUnresolvedImportsList; var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, unresolvedImports, hasChanges); @@ -79804,7 +81237,7 @@ var ts; fileWatcher.close(); } }); - var _loop_8 = function (missingFilePath) { + var _loop_9 = function (missingFilePath) { if (!this_1.missingFilesMap.has(missingFilePath)) { var fileWatcher_1 = this_1.projectService.host.watchFile(missingFilePath, function (_filename, eventKind) { if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { @@ -79820,7 +81253,7 @@ var ts; var this_1 = this; for (var _b = 0, missingFilePaths_1 = missingFilePaths; _b < missingFilePaths_1.length; _b++) { var missingFilePath = missingFilePaths_1[_b]; - _loop_8(missingFilePath); + _loop_9(missingFilePath); } } var oldExternalFiles = this.externalFiles || server.emptyArray; @@ -79984,10 +81417,11 @@ var ts; server.Project = Project; var InferredProject = (function (_super) { __extends(InferredProject, _super); - function InferredProject(projectService, documentRegistry, compilerOptions) { + function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath) { var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, true, compilerOptions, false) || this; _this._isJsInferredProject = false; _this.directoriesWatchedForTsconfig = []; + _this.projectRootPath = projectRootPath; return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -80091,7 +81525,7 @@ var ts; } } if (this.projectService.globalPlugins) { - var _loop_9 = function (globalPluginName) { + var _loop_10 = function (globalPluginName) { if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths); @@ -80099,7 +81533,7 @@ var ts; var this_2 = this; for (var _b = 0, _c = this.projectService.globalPlugins; _b < _c.length; _b++) { var globalPluginName = _c[_b]; - _loop_9(globalPluginName); + _loop_10(globalPluginName); } } }; @@ -80222,10 +81656,12 @@ var ts; } this.typeRootsWatchers = undefined; } - this.directoriesWatchedForWildcards.forEach(function (watcher) { - watcher.close(); - }); - this.directoriesWatchedForWildcards = undefined; + if (this.directoriesWatchedForWildcards) { + this.directoriesWatchedForWildcards.forEach(function (watcher) { + watcher.close(); + }); + this.directoriesWatchedForWildcards = undefined; + } this.stopWatchingDirectory(); }; ConfiguredProject.prototype.addOpenRef = function () { @@ -80248,8 +81684,12 @@ var ts; _this.externalProjectName = externalProjectName; _this.compileOnSaveEnabled = compileOnSaveEnabled; _this.projectFilePath = projectFilePath; + _this.excludedFiles = []; return _this; } + ExternalProject.prototype.getExcludedFiles = function () { + return this.excludedFiles; + }; ExternalProject.prototype.getProjectRootPath = function () { if (this.projectFilePath) { return ts.getDirectoryPath(this.projectFilePath); @@ -80455,6 +81895,7 @@ var ts; this.inferredProjects = []; this.configuredProjects = []; this.openFiles = []; + this.compilerOptionsForInferredProjectsPerProjectRoot = ts.createMap(); this.projectToSizeMap = ts.createMap(); this.safelist = defaultTypeSafeList; this.seenProjects = ts.createMap(); @@ -80462,16 +81903,21 @@ var ts; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; this.useSingleInferredProject = opts.useSingleInferredProject; + this.useInferredProjectPerProjectRoot = opts.useInferredProjectPerProjectRoot; this.typingsInstaller = opts.typingsInstaller || server.nullTypingsInstaller; this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds; this.eventHandler = opts.eventHandler; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.host.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.directoryWatchers = new DirectoryWatchers(this); this.throttledOperations = new server.ThrottledOperations(this.host); + if (opts.typesMapLocation) { + this.loadTypesMap(); + } this.typingsInstaller.attach(this); this.typingsCache = new server.TypingsCache(this.typingsInstaller); this.hostConfiguration = { @@ -80494,10 +81940,30 @@ var ts; if (!this.eventHandler) { return; } - this.eventHandler({ + var event = { eventName: server.ProjectLanguageServiceStateEvent, data: { project: project, languageServiceEnabled: languageServiceEnabled } - }); + }; + this.eventHandler(event); + }; + ProjectService.prototype.loadTypesMap = function () { + try { + var fileContent = this.host.readFile(this.typesMapLocation); + if (fileContent === undefined) { + this.logger.info("Provided types map file \"" + this.typesMapLocation + "\" doesn't exist"); + return; + } + var raw = JSON.parse(fileContent); + for (var _i = 0, _a = Object.keys(raw.typesMap); _i < _a.length; _i++) { + var k = _a[_i]; + raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i"); + } + this.safelist = raw.typesMap; + } + catch (e) { + this.logger.info("Error loading types map: " + e); + this.safelist = defaultTypeSafeList; + } }; ProjectService.prototype.updateTypingsForProject = function (response) { var project = this.findProject(response.projectName); @@ -80514,16 +81980,28 @@ var ts; } project.updateGraph(); }; - ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { - this.compilerOptionsForInferredProjects = convertCompilerOptions(projectCompilerOptions); - this.compilerOptionsForInferredProjects.allowNonTsExtensions = true; - this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; - for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - proj.setCompilerOptions(this.compilerOptionsForInferredProjects); - proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; + ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) { + ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); + var compilerOptions = convertCompilerOptions(projectCompilerOptions); + compilerOptions.allowNonTsExtensions = true; + if (projectRootPath) { + this.compilerOptionsForInferredProjectsPerProjectRoot.set(projectRootPath, compilerOptions); } - this.updateProjectGraphs(this.inferredProjects); + else { + this.compilerOptionsForInferredProjects = compilerOptions; + } + var updatedProjects = []; + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var project = _a[_i]; + if (projectRootPath ? + project.projectRootPath === projectRootPath : + !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { + project.setCompilerOptions(compilerOptions); + project.compileOnSaveEnabled = compilerOptions.compileOnSave; + updatedProjects.push(project); + } + } + this.updateProjectGraphs(updatedProjects); }; ProjectService.prototype.stopWatchingDirectory = function (directory) { this.directoryWatchers.stopWatchingDirectory(directory); @@ -80630,10 +82108,11 @@ var ts; } for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { var openFile = _a[_i]; - this.eventHandler({ + var event_1 = { eventName: server.ContextEvent, data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } - }); + }; + this.eventHandler(event_1); } } this.printProjects(); @@ -80705,7 +82184,7 @@ var ts; break; } }; - ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) { + ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles, projectRootPath) { var externalProject = this.findContainingExternalProject(info.fileName); if (externalProject) { if (addToListOfOpenFiles) { @@ -80730,19 +82209,19 @@ var ts; return; } if (info.containingProjects.length === 0) { - var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info); - if (!this.useSingleInferredProject) { + var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info, projectRootPath); + if (!this.useSingleInferredProject && !inferredProject.projectRootPath) { for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { var f = _c[_b]; if (f.containingProjects.length === 0 || !inferredProject.containsScriptInfo(f)) { continue; } for (var _d = 0, _e = f.containingProjects; _d < _e.length; _d++) { - var fContainingProject = _e[_d]; - if (fContainingProject.projectKind === server.ProjectKind.Inferred && - fContainingProject.isRoot(f) && - fContainingProject !== inferredProject) { - this.removeProject(fContainingProject); + var containingProject = _e[_d]; + if (containingProject.projectKind === server.ProjectKind.Inferred && + containingProject !== inferredProject && + containingProject.isRoot(f)) { + this.removeProject(containingProject); f.attachToProject(inferredProject); } } @@ -80853,31 +82332,32 @@ var ts; return undefined; }; ProjectService.prototype.printProjects = function () { + var _this = this; if (!this.logger.hasLevel(server.LogLevel.verbose)) { return; } this.logger.startGroup(); var counter = 0; - counter = printProjects(this.logger, this.externalProjects, counter); - counter = printProjects(this.logger, this.configuredProjects, counter); - counter = printProjects(this.logger, this.inferredProjects, counter); + var printProjects = function (projects, counter) { + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var project = projects_4[_i]; + project.updateGraph(); + _this.logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); + _this.logger.info(project.filesToString()); + _this.logger.info("-----------------------------------------------"); + counter++; + } + return counter; + }; + counter = printProjects(this.externalProjects, counter); + counter = printProjects(this.configuredProjects, counter); + printProjects(this.inferredProjects, counter); this.logger.info("Open files: "); for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { var rootFile = _a[_i]; this.logger.info("\t" + rootFile.fileName); } this.logger.endGroup(); - function printProjects(logger, projects, counter) { - for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { - var project = projects_4[_i]; - project.updateGraph(); - logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); - logger.info(project.filesToString()); - logger.info("-----------------------------------------------"); - counter++; - } - return counter; - } }; ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { configFileName = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); @@ -80998,10 +82478,11 @@ var ts; if (!this.eventHandler) { return; } - this.eventHandler({ + var event = { eventName: server.ConfigFileDiagEvent, - data: { configFileName: configFileName, diagnostics: diagnostics || [], triggerFile: triggerFile } - }); + data: { configFileName: configFileName, diagnostics: diagnostics || server.emptyArray, triggerFile: triggerFile } + }; + this.eventHandler(event); }; ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { var _this = this; @@ -81150,18 +82631,60 @@ var ts; } return configFileErrors; }; - ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) { + ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (root, projectRootPath) { + if (!this.useInferredProjectPerProjectRoot) { + return undefined; + } + if (projectRootPath) { + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var project = _a[_i]; + if (project.projectRootPath === projectRootPath) { + return project; + } + } + return this.createInferredProject(false, projectRootPath); + } + var bestMatch; + for (var _b = 0, _c = this.inferredProjects; _b < _c.length; _b++) { + var project = _c[_b]; + if (!project.projectRootPath) + continue; + if (!ts.containsPath(project.projectRootPath, root.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) + continue; + if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) + continue; + bestMatch = project; + } + return bestMatch; + }; + ProjectService.prototype.getOrCreateSingleInferredProjectIfEnabled = function () { + if (!this.useSingleInferredProject) { + return undefined; + } + if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === undefined) { + return this.inferredProjects[0]; + } + return this.createInferredProject(true); + }; + ProjectService.prototype.createInferredProject = function (isSingleInferredProject, projectRootPath) { + var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; + var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath); + if (isSingleInferredProject) { + this.inferredProjects.unshift(project); + } + else { + this.inferredProjects.push(project); + } + return project; + }; + ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root, projectRootPath) { var _this = this; - var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length; - var project = useExistingProject - ? this.inferredProjects[0] - : new server.InferredProject(this, this.documentRegistry, this.compilerOptionsForInferredProjects); + var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(root, projectRootPath) || + this.getOrCreateSingleInferredProjectIfEnabled() || + this.createInferredProject(); project.addRoot(root); this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); project.updateGraph(); - if (!useExistingProject) { - this.inferredProjects.push(project); - } return project; }; ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { @@ -81294,7 +82817,7 @@ var ts; project.markAsDirty(); } var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); - this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.assignScriptInfoToInferredProjectIfNecessary(info, true, projectRootPath); this.deleteOrphanScriptInfoNotInAnyProject(); this.printProjects(); return { configFileName: configFileName, configFileErrors: configFileErrors }; @@ -81308,13 +82831,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_10 = function (proj) { + var _loop_11 = function (proj) { var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_10(proj); + _loop_11(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -81419,26 +82942,19 @@ var ts; ProjectService.prototype.resetSafeList = function () { this.safelist = defaultTypeSafeList; }; - ProjectService.prototype.loadSafeList = function (fileName) { - var raw = JSON.parse(this.host.readFile(fileName, "utf-8")); - for (var _i = 0, _a = Object.keys(raw); _i < _a.length; _i++) { - var k = _a[_i]; - raw[k].match = new RegExp(raw[k].match, "i"); - } - this.safelist = raw; - }; ProjectService.prototype.applySafeList = function (proj) { var _this = this; var rootFiles = proj.rootFiles, typeAcquisition = proj.typeAcquisition; var types = (typeAcquisition && typeAcquisition.include) || []; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); - var _loop_11 = function (name) { - var rule = this_3.safelist[name]; + var excludedFiles = []; + var _loop_12 = function (name_70) { + var rule = this_3.safelist[name_70]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; if (rule.match.test(root)) { - this_3.logger.info("Excluding files based on rule " + name); + this_3.logger.info("Excluding files based on rule " + name_70); if (rule.types) { for (var _a = 0, _b = rule.types; _a < _b.length; _a++) { var type = _b[_a]; @@ -81448,7 +82964,7 @@ var ts; } } if (rule.exclude) { - var _loop_12 = function (exclude) { + var _loop_13 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -81457,7 +82973,7 @@ var ts; return exclude.map(function (groupNumberOrString) { if (typeof groupNumberOrString === "number") { if (typeof groups[groupNumberOrString] !== "string") { - _this.logger.info("Incorrect RegExp specification in safelist rule " + name + " - not enough groups"); + _this.logger.info("Incorrect RegExp specification in safelist rule " + name_70 + " - not enough groups"); return "\\*"; } return ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]); @@ -81471,7 +82987,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_12(exclude); + _loop_13(exclude); } } else { @@ -81489,11 +83005,24 @@ var ts; }; var this_3 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { - var name = _a[_i]; - _loop_11(name); + var name_70 = _a[_i]; + _loop_12(name_70); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); - proj.rootFiles = proj.rootFiles.filter(function (_file, index) { return !excludeRegexes.some(function (re) { return re.test(normalizedNames[index]); }); }); + var filesToKeep = []; + var _loop_14 = function (i) { + if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { + excludedFiles.push(normalizedNames[i]); + } + else { + filesToKeep.push(proj.rootFiles[i]); + } + }; + for (var i = 0; i < proj.rootFiles.length; i++) { + _loop_14(i); + } + proj.rootFiles = filesToKeep; + return excludedFiles; }; ProjectService.prototype.openExternalProject = function (proj, suppressRefreshOfInferredProjects) { if (suppressRefreshOfInferredProjects === void 0) { suppressRefreshOfInferredProjects = false; } @@ -81501,7 +83030,7 @@ var ts; var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions); proj.typeAcquisition = typeAcquisition; } - this.applySafeList(proj); + var excludedFiles = this.applySafeList(proj); var tsConfigFiles; var rootFiles = []; for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { @@ -81522,6 +83051,7 @@ var ts; var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); var exisingConfigFiles; if (externalProject) { + externalProject.excludedFiles = excludedFiles; if (!tsConfigFiles) { var compilerOptions = convertCompilerOptions(proj.options); if (this.exceededTotalSizeLimitForNonTsFiles(proj.projectFileName, compilerOptions, proj.rootFiles, externalFilePropertyReader)) { @@ -81580,7 +83110,8 @@ var ts; } else { this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition); + var newProj = this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition); + newProj.excludedFiles = excludedFiles; } if (!suppressRefreshOfInferredProjects) { this.refreshInferredProjects(); @@ -81953,6 +83484,10 @@ var ts; var _this = this; return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); }); }; + LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) { + var _this = this; + return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); }); + }; LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options) { var _this = this; return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () { @@ -82248,4 +83783,6 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "2.5"; +var toolsVersion = "2.6"; + +//# sourceMappingURL=tsserverlibrary.js.map diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 1ca5c4d773..dd56f51d4a 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -1210,7 +1210,7 @@ declare namespace ts { interface CatchClause extends Node { kind: SyntaxKind.CatchClause; parent?: TryStatement; - variableDeclaration: VariableDeclaration; + variableDeclaration?: VariableDeclaration; block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; @@ -1496,38 +1496,39 @@ declare namespace ts { interface FlowLock { locked?: boolean; } - interface AfterFinallyFlow extends FlowNode, FlowLock { + interface AfterFinallyFlow extends FlowNodeBase, FlowLock { antecedent: FlowNode; } - interface PreFinallyFlow extends FlowNode { + interface PreFinallyFlow extends FlowNodeBase { antecedent: FlowNode; lock: FlowLock; } - interface FlowNode { + type FlowNode = AfterFinallyFlow | PreFinallyFlow | FlowStart | FlowLabel | FlowAssignment | FlowCondition | FlowSwitchClause | FlowArrayMutation; + interface FlowNodeBase { flags: FlowFlags; id?: number; } - interface FlowStart extends FlowNode { + interface FlowStart extends FlowNodeBase { container?: FunctionExpression | ArrowFunction | MethodDeclaration; } - interface FlowLabel extends FlowNode { + interface FlowLabel extends FlowNodeBase { antecedents: FlowNode[]; } - interface FlowAssignment extends FlowNode { + interface FlowAssignment extends FlowNodeBase { node: Expression | VariableDeclaration | BindingElement; antecedent: FlowNode; } - interface FlowCondition extends FlowNode { + interface FlowCondition extends FlowNodeBase { expression: Expression; antecedent: FlowNode; } - interface FlowSwitchClause extends FlowNode { + interface FlowSwitchClause extends FlowNodeBase { switchStatement: SwitchStatement; clauseStart: number; clauseEnd: number; antecedent: FlowNode; } - interface FlowArrayMutation extends FlowNode { + interface FlowArrayMutation extends FlowNodeBase { node: CallExpression | BinaryExpression; antecedent: FlowNode; } @@ -1696,6 +1697,15 @@ declare namespace ts { getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + /** + * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. + * Otherwise returns its input. + * For example, at `export type T = number;`: + * - `getSymbolAtLocation` at the location `T` will return the exported symbol for `T`. + * - But the result of `getSymbolsInScope` will contain the *local* symbol for `T`, not the exported symbol. + * - Calling `getExportSymbolOfSymbol` on that local symbol will return the exported symbol. + */ + getExportSymbolOfSymbol(symbol: Symbol): Symbol; getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; @@ -1790,11 +1800,11 @@ declare namespace ts { UseFullyQualifiedType = 256, InFirstTypeArgument = 512, InTypeAlias = 1024, - UseTypeAliasValue = 2048, SuppressAnyReturnType = 4096, AddUndefined = 8192, WriteClassExpressionAsTypeLiteral = 16384, InArrayType = 32768, + UseAliasDefinedOutsideCurrentScope = 65536, } enum SymbolFormatFlags { None = 0, @@ -2056,6 +2066,7 @@ declare namespace ts { interface TypeVariable extends Type { } interface TypeParameter extends TypeVariable { + /** Retrieve using getConstraintFromTypeParameter */ constraint: Type; default?: Type; } @@ -2103,6 +2114,21 @@ declare namespace ts { NoDefault = 2, AnyDefault = 4, } + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ + enum Ternary { + False = 0, + Maybe = 1, + True = -1, + } + type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary; interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; @@ -2195,6 +2221,7 @@ declare namespace ts { outFile?: string; paths?: MapLike; preserveConstEnums?: boolean; + preserveSymlinks?: boolean; project?: string; reactNamespace?: string; jsxFactory?: string; @@ -2300,6 +2327,10 @@ declare namespace ts { readFile(fileName: string): string | undefined; trace?(s: string): void; directoryExists?(directoryName: string): boolean; + /** + * Resolve a symbolic link. + * @see https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options + */ realpath?(path: string): string; getCurrentDirectory?(): string; getDirectories?(path: string): string[]; @@ -2314,17 +2345,13 @@ declare namespace ts { interface ResolvedModule { /** Path of the file the module was resolved to. */ resolvedFileName: string; - /** - * Denotes if 'resolvedFileName' is isExternalLibraryImport and thus should be a proper external module: - * - be a .d.ts file - * - use top level imports\exports - * - don't use tripleslash references - */ + /** True if `resolvedFileName` comes from `node_modules`. */ isExternalLibraryImport?: boolean; } /** * ResolvedModule with an explicitly provided `extension` property. * Prefer this over `ResolvedModule`. + * If changing this, remember to change `moduleResolutionIsEqualTo`. */ interface ResolvedModuleFull extends ResolvedModule { /** @@ -2332,6 +2359,21 @@ declare namespace ts { * This is optional for backwards-compatibility, but will be added if not provided. */ extension: Extension; + packageId?: PackageId; + } + /** + * Unique identifier with a package name and version. + * If changing this, remember to change `packageIdIsEqual`. + */ + interface PackageId { + /** + * Name of the package. + * Should not include `@types`. + * If accessing a non-index file, this should include its name e.g. "foo/bar". + */ + name: string; + /** Version of the package, e.g. "1.2.3" */ + version: string; } enum Extension { Ts = ".ts", @@ -2593,7 +2635,7 @@ declare namespace ts { } } declare namespace ts { - const versionMajorMinor = "2.5"; + const versionMajorMinor = "2.6"; /** The version of the TypeScript compiler release */ const version: string; } @@ -2741,6 +2783,8 @@ declare namespace ts { function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: Node): boolean; + function isEmptyBindingPattern(node: BindingName): node is BindingPattern; + function isEmptyBindingElement(node: BindingElement): boolean; function getCombinedModifierFlags(node: Node): ModifierFlags; function getCombinedNodeFlags(node: Node): NodeFlags; /** @@ -3310,8 +3354,8 @@ declare namespace ts { function updateDefaultClause(node: DefaultClause, statements: ReadonlyArray): DefaultClause; function createHeritageClause(token: HeritageClause["token"], types: ReadonlyArray): HeritageClause; function updateHeritageClause(node: HeritageClause, types: ReadonlyArray): HeritageClause; - function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; - function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; + function createCatchClause(variableDeclaration: string | VariableDeclaration | undefined, block: Block): CatchClause; + function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression): PropertyAssignment; function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression): ShorthandPropertyAssignment; @@ -3773,6 +3817,7 @@ declare namespace ts { getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; + getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; diff --git a/lib/typescript.js b/lib/typescript.js index eb71a73ba4..f1356d558c 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -511,7 +511,7 @@ var ts; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); - var OperationCanceledException = (function () { + var OperationCanceledException = /** @class */ (function () { function OperationCanceledException() { } return OperationCanceledException; @@ -570,11 +570,12 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 2048] = "UseTypeAliasValue"; TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + // even though `T` can't be accessed in the current scope. })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -860,6 +861,21 @@ var ts; InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ var SpecialPropertyAssignmentKind; (function (SpecialPropertyAssignmentKind) { @@ -1329,27 +1345,12 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "2.5"; + ts.versionMajorMinor = "2.6"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); /* @internal */ (function (ts) { - /** - * Ternary values are defined such that - * x & y is False if either x or y is False. - * x & y is Maybe if either x or y is Maybe, but neither x or y is False. - * x & y is True if both x and y are True. - * x | y is False if both x and y are False. - * x | y is Maybe if either x or y is Maybe, but neither x or y is True. - * x | y is True if either x or y is True. - */ - var Ternary; - (function (Ternary) { - Ternary[Ternary["False"] = 0] = "False"; - Ternary[Ternary["Maybe"] = 1] = "Maybe"; - Ternary[Ternary["True"] = -1] = "True"; - })(Ternary = ts.Ternary || (ts.Ternary = {})); // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(/*locales*/ undefined, { usage: "sort", sensitivity: "accent" }) : undefined; // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". @@ -1403,7 +1404,7 @@ var ts; var MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); // Keep the class inside a function so it doesn't get compiled if it's not used. function shimMap() { - var MapIterator = (function () { + var MapIterator = /** @class */ (function () { function MapIterator(data, selector) { this.index = 0; this.data = data; @@ -1420,7 +1421,7 @@ var ts; }; return MapIterator; }()); - return (function () { + return /** @class */ (function () { function class_1() { this.data = createDictionaryObject(); this.size = 0; @@ -1668,10 +1669,9 @@ var ts; ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (f(item)) { - array[outIndex] = item; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; outIndex++; } } @@ -1722,8 +1722,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1799,11 +1799,13 @@ var ts; ts.sameFlatMap = sameFlatMap; function mapDefined(array, mapFn) { var result = []; - for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); - if (mapped !== undefined) { - result.push(mapped); + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } } } return result; @@ -1882,8 +1884,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; if (predicate(v)) { return true; } @@ -1909,8 +1911,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var item = array_6[_i]; + loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -2003,8 +2005,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var v = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; // Note: we need the following type assertion because of GH #17069 result += v[prop]; } @@ -2336,8 +2338,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var value = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -2502,11 +2504,11 @@ var ts; ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { var end = start + length; - Debug.assert(start >= 0, "start must be non-negative, is " + start); - Debug.assert(length >= 0, "length must be non-negative, is " + length); + Debug.assertGreaterThanOrEqual(start, 0); + Debug.assertGreaterThanOrEqual(length, 0); if (file) { - Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); - Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + Debug.assertLessThanOrEqual(start, file.text.length); + Debug.assertLessThanOrEqual(end, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -2736,19 +2738,23 @@ var ts; return normalized; } function normalizePath(path) { + return normalizePathAndParts(path).path; + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { path = normalizeSlashes(path); var rootLength = getRootLength(path); var root = path.substr(0, rootLength); - var normalized = getNormalizedParts(path, rootLength); - if (normalized.length) { - var joinedParts = root + normalized.join(ts.directorySeparator); - return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts; + var parts = getNormalizedParts(path, rootLength); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; } else { - return root; + return { path: root, parts: parts }; } } - ts.normalizePath = normalizePath; + ts.normalizePathAndParts = normalizePathAndParts; /** A path ending with '/' refers to a directory only, never a file. */ function pathEndsWithDirectorySeparator(path) { return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; @@ -3055,14 +3061,43 @@ var ts; // proof. var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - /** - * Matches any single directory segment unless it is the last segment and a .min.js file - * Breakdown: - * [^./] # matches everything up to the first . character (excluding directory seperators) - * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension - */ - var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; - var singleAsteriskRegexFragmentOther = "[^/]*"; + /* @internal */ + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + /** + * Matches any single directory segment unless it is the last segment and a .min.js file + * Breakdown: + * [^./] # matches everything up to the first . character (excluding directory seperators) + * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension + */ + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; function getRegularExpressionForWildcard(specs, basePath, usage) { var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); if (!patterns || !patterns.length) { @@ -3078,15 +3113,8 @@ var ts; if (specs === undefined || specs.length === 0) { return undefined; } - var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; - var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; - /** - * Regex for the ** wildcard. Matches any number of subdirectories. When used for including - * files or directories, does not match subdirectories that start with a . character - */ - var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; return flatMap(specs, function (spec) { - return spec && getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } /** @@ -3097,7 +3125,8 @@ var ts; return !/[.*?]/.test(lastPathComponent); } ts.isImplicitGlob = isImplicitGlob; - function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; @@ -3131,19 +3160,33 @@ var ts; subpattern += ts.directorySeparator; } if (usage !== "exclude") { + var componentPattern = ""; // The * and ? wildcards should not match directories or files that start with . if they // appear first in a component. Dotted directories and files can be included explicitly // like so: **/.*/.* if (component.charCodeAt(0) === 42 /* asterisk */) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; component = component.substr(1); } else if (component.charCodeAt(0) === 63 /* question */) { - subpattern += "[^./]"; + componentPattern += "[^./]"; component = component.substr(1); } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + // Patterns should not include subfolders like node_modules unless they are + // explicitly included as part of the path. + // + // As an optimization, if the component pattern is the same as the component, + // then there definitely were no wildcard characters and we do not need to + // add the exclusion pattern. + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } hasWrittenComponent = true; } @@ -3153,12 +3196,6 @@ var ts; } return subpattern; } - function replaceWildCardCharacterFiles(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); - } - function replaceWildCardCharacterOther(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); - } function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } @@ -3319,14 +3356,7 @@ var ts; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = allSupportedExtensions.slice(0); - for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { - var extInfo = extraFileExtensions_1[_i]; - if (extensions.indexOf(extInfo.extension) === -1) { - extensions.push(extInfo.extension); - } - } - return extensions; + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -3481,12 +3511,37 @@ var ts; function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { if (verboseDebugInfo) { - message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); } fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; function fail(message, stackCrawlMark) { debugger; var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); @@ -3652,6 +3707,10 @@ var ts; Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; function tryGetExtensionFromPath(path) { return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } @@ -3664,6 +3723,18 @@ var ts; /// var ts; (function (ts) { + /** + * Set a high stack trace limit to provide more information in case of an error. + * Called for command-line and server use cases. + * Not called if TypeScript is used as a library. + */ + /* @internal */ + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; var FileWatcherEventKind; (function (FileWatcherEventKind) { FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; @@ -3714,7 +3785,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -4569,6 +4640,8 @@ var ts; Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4756,6 +4829,7 @@ var ts; Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -5009,6 +5083,8 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), + Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), }; })(ts || (ts = {})); /// @@ -6812,19 +6888,6 @@ var ts; return undefined; } ts.getDeclarationOfKind = getDeclarationOfKind; - function findDeclaration(symbol, predicate) { - var declarations = symbol.declarations; - if (declarations) { - for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { - var declaration = declarations_2[_i]; - if (predicate(declaration)) { - return declaration; - } - } - } - return undefined; - } - ts.findDeclaration = findDeclaration; var stringWriter = createSingleLineStringWriter(); var stringWriterAcquired = false; function createSingleLineStringWriter() { @@ -6886,19 +6949,20 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; - /* @internal */ function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && - oldResolution.resolvedFileName === newResolution.resolvedFileName; + oldResolution.resolvedFileName === newResolution.resolvedFileName && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; - /* @internal */ + function packageIdIsEqual(a, b) { + return a === b || a && b && a.name === b.name && a.version === b.version; + } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; - /* @internal */ function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { @@ -6968,14 +7032,6 @@ var ts; return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; } ts.nodePosToString = nodePosToString; - function getStartPosOfNode(node) { - return node.pos; - } - ts.getStartPosOfNode = getStartPosOfNode; - function isDefined(value) { - return value !== undefined; - } - ts.isDefined = isDefined; function getEndLinePosition(line, sourceFile) { ts.Debug.assert(line >= 0); var lineStarts = ts.getLineStarts(sourceFile); @@ -7025,6 +7081,32 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (text.charCodeAt(commentPos + 1) === 47 /* slash */ && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47 /* slash */) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, comment) { + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + } + ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* // want to skip trivia because this will launch us forward to the next token. @@ -7094,15 +7176,20 @@ var ts; // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { case 9 /* StringLiteral */: - return '"' + escapeText(node.text) + '"'; + if (node.singleQuote) { + return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; + } + else { + return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + } case 13 /* NoSubstitutionTemplateLiteral */: - return "`" + escapeText(node.text) + "`"; + return "`" + escapeText(node.text, 96 /* backtick */) + "`"; case 14 /* TemplateHead */: - return "`" + escapeText(node.text) + "${"; + return "`" + escapeText(node.text, 96 /* backtick */) + "${"; case 15 /* TemplateMiddle */: - return "}" + escapeText(node.text) + "${"; + return "}" + escapeText(node.text, 96 /* backtick */) + "${"; case 16 /* TemplateTail */: - return "}" + escapeText(node.text) + "`"; + return "}" + escapeText(node.text, 96 /* backtick */) + "`"; case 8 /* NumericLiteral */: return node.text; } @@ -7191,6 +7278,7 @@ var ts; return ts.isExternalModule(node) || compilerOptions.isolatedModules; } ts.isEffectiveExternalModule = isEffectiveExternalModule; + /* @internal */ function isBlockScope(node, parentNode) { switch (node.kind) { case 265 /* SourceFile */: @@ -7381,13 +7469,9 @@ var ts; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); + return node.kind !== 10 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; - function getLeadingCommentRangesOfNodeFromText(node, text) { - return ts.getLeadingCommentRanges(text, node.pos); - } - ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; function getJSDocCommentRanges(node, text) { var commentRanges = (node.kind === 146 /* Parameter */ || node.kind === 145 /* TypeParameter */ || @@ -7395,7 +7479,7 @@ var ts; node.kind === 187 /* ArrowFunction */ || node.kind === 185 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : - getLeadingCommentRangesOfNodeFromText(node, text); + ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' return ts.filter(commentRanges, function (comment) { return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && @@ -7405,8 +7489,9 @@ var ts; } ts.getJSDocCommentRanges = getJSDocCommentRanges; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; - ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { if (158 /* FirstTypeNode */ <= node.kind && node.kind <= 173 /* LastTypeNode */) { return true; @@ -7660,21 +7745,11 @@ var ts; } ts.getPropertyAssignment = getPropertyAssignment; function getContainingFunction(node) { - while (true) { - node = node.parent; - if (!node || ts.isFunctionLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isFunctionLike); } ts.getContainingFunction = getContainingFunction; function getContainingClass(node) { - while (true) { - node = node.parent; - if (!node || ts.isClassLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isClassLike); } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { @@ -8570,14 +8645,14 @@ var ts; ts.getAncestor = getAncestor; function getFileReferenceFromReferencePath(comment, commentRange) { var simpleReferenceRegEx = /^\/\/\/\s*/gim; + var isNoDefaultLibRegEx = new RegExp(defaultLibReferenceRegEx.source, "gim"); if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); - var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); + var refLibResult = !refMatchResult && fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); var match = refMatchResult || refLibResult; if (match) { var pos = commentRange.pos + match[1].length + match[2].length; @@ -8782,10 +8857,6 @@ var ts; return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } ts.getOriginalSourceFile = getOriginalSourceFile; - function getOriginalSourceFiles(sourceFiles) { - return ts.sameMap(sourceFiles, getOriginalSourceFile); - } - ts.getOriginalSourceFiles = getOriginalSourceFiles; var Associativity; (function (Associativity) { Associativity[Associativity["Left"] = 0] = "Left"; @@ -9029,7 +9100,9 @@ var ts; // the language service. These characters should be escaped when printing, and if any characters are added, // the map below must be updated. Note that this regexp *does not* include the 'delete' character. // There is no reason for this other than that JSON.stringify does not handle it either. - var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\0": "\\0", "\t": "\\t", @@ -9040,6 +9113,8 @@ var ts; "\n": "\\n", "\\": "\\\\", "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" // nextLine @@ -9049,7 +9124,10 @@ var ts; * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) * Note that this doesn't actually wrap the input in double quotes. */ - function escapeString(s) { + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; return s.replace(escapedCharsRegExp, getReplacement); } ts.escapeString = escapeString; @@ -9069,8 +9147,8 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiString(s) { - s = escapeString(s); + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. return nonAsciiCharacters.test(s) ? @@ -9455,7 +9533,7 @@ var ts; // // var x = 10; if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); } } else { @@ -9495,9 +9573,8 @@ var ts; } } return currentDetachedCommentInfo; - function isPinnedComment(comment) { - return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment); } } ts.emitDetachedComments = emitDetachedComments; @@ -9593,9 +9670,13 @@ var ts; } ts.hasModifiers = hasModifiers; function hasModifier(node, flags) { - return (getModifierFlags(node) & flags) !== 0; + return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; function getModifierFlags(node) { if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; @@ -9673,23 +9754,6 @@ var ts; return false; } ts.isDestructuringAssignment = isDestructuringAssignment; - // Returns false if this heritage clause element's expression contains something unsupported - // (i.e. not a name or dotted name). - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 71 /* Identifier */) { - return true; - } - else if (ts.isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } - } function isExpressionWithTypeArgumentsInClassExtendsClause(node) { return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } @@ -9816,78 +9880,6 @@ var ts; return carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; - /** - * Tests whether a node and its subtree is simple enough to have its position - * information ignored when emitting source maps in a destructuring assignment. - * - * @param node The expression to test. - */ - function isSimpleExpression(node) { - return isSimpleExpressionWorker(node, 0); - } - ts.isSimpleExpression = isSimpleExpression; - function isSimpleExpressionWorker(node, depth) { - if (depth <= 5) { - var kind = node.kind; - if (kind === 9 /* StringLiteral */ - || kind === 8 /* NumericLiteral */ - || kind === 12 /* RegularExpressionLiteral */ - || kind === 13 /* NoSubstitutionTemplateLiteral */ - || kind === 71 /* Identifier */ - || kind === 99 /* ThisKeyword */ - || kind === 97 /* SuperKeyword */ - || kind === 101 /* TrueKeyword */ - || kind === 86 /* FalseKeyword */ - || kind === 95 /* NullKeyword */) { - return true; - } - else if (kind === 179 /* PropertyAccessExpression */) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 180 /* ElementAccessExpression */) { - return isSimpleExpressionWorker(node.expression, depth + 1) - && isSimpleExpressionWorker(node.argumentExpression, depth + 1); - } - else if (kind === 192 /* PrefixUnaryExpression */ - || kind === 193 /* PostfixUnaryExpression */) { - return isSimpleExpressionWorker(node.operand, depth + 1); - } - else if (kind === 194 /* BinaryExpression */) { - return node.operatorToken.kind !== 40 /* AsteriskAsteriskToken */ - && isSimpleExpressionWorker(node.left, depth + 1) - && isSimpleExpressionWorker(node.right, depth + 1); - } - else if (kind === 195 /* ConditionalExpression */) { - return isSimpleExpressionWorker(node.condition, depth + 1) - && isSimpleExpressionWorker(node.whenTrue, depth + 1) - && isSimpleExpressionWorker(node.whenFalse, depth + 1); - } - else if (kind === 190 /* VoidExpression */ - || kind === 189 /* TypeOfExpression */ - || kind === 188 /* DeleteExpression */) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 177 /* ArrayLiteralExpression */) { - return node.elements.length === 0; - } - else if (kind === 178 /* ObjectLiteralExpression */) { - return node.properties.length === 0; - } - else if (kind === 181 /* CallExpression */) { - if (!isSimpleExpressionWorker(node.expression, depth + 1)) { - return false; - } - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (!isSimpleExpressionWorker(argument, depth + 1)) { - return false; - } - } - return true; - } - } - return false; - } /** * Formats an enum value as a string for debugging and debug assertions. */ @@ -9959,24 +9951,6 @@ var ts; return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true); } ts.formatObjectFlags = formatObjectFlags; - function getRangePos(range) { - return range ? range.pos : -1; - } - ts.getRangePos = getRangePos; - function getRangeEnd(range) { - return range ? range.end : -1; - } - ts.getRangeEnd = getRangeEnd; - /** - * Increases (or decreases) a position by the provided amount. - * - * @param pos The position. - * @param value The delta. - */ - function movePos(pos, value) { - return ts.positionIsSynthesized(pos) ? -1 : pos + value; - } - ts.movePos = movePos; /** * Creates a new TextRange from the provided pos and end. * @@ -10034,26 +10008,6 @@ var ts; return range.pos === range.end; } ts.isCollapsedRange = isCollapsedRange; - /** - * Creates a new TextRange from a provided range with its end position collapsed to its - * start position. - * - * @param range A TextRange. - */ - function collapseRangeToStart(range) { - return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); - } - ts.collapseRangeToStart = collapseRangeToStart; - /** - * Creates a new TextRange from a provided range with its start position collapsed to its - * end position. - * - * @param range A TextRange. - */ - function collapseRangeToEnd(range) { - return isCollapsedRange(range) ? range : moveRangePos(range, range.end); - } - ts.collapseRangeToEnd = collapseRangeToEnd; /** * Creates a new TextRange for a token at the provides start position. * @@ -10116,31 +10070,6 @@ var ts; function isInitializedVariable(node) { return node.initializer !== undefined; } - /** - * Gets a value indicating whether a node is merged with a class declaration in the same scope. - */ - function isMergedWithClass(node) { - if (node.symbol) { - for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 229 /* ClassDeclaration */ && declaration !== node) { - return true; - } - } - } - return false; - } - ts.isMergedWithClass = isMergedWithClass; - /** - * Gets a value indicating whether a node is the first declaration of its kind. - * - * @param node A Declaration node. - * @param kind The SyntaxKind to find among related declarations. - */ - function isFirstDeclarationOfKind(node, kind) { - return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; - } - ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; function isWatchSet(options) { // Firefox has Object.prototype.watch return options.watch && options.hasOwnProperty("watch"); @@ -10434,6 +10363,20 @@ var ts; return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 152 /* Constructor */ && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { while (node && (node.kind === 176 /* BindingElement */ || ts.isBindingPattern(node))) { node = node.parent; @@ -11618,6 +11561,19 @@ var ts; return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + /* @internal */ + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 193 /* PostfixUnaryExpression */: + return true; + case 192 /* PrefixUnaryExpression */: + return expr.operator === 43 /* PlusPlusToken */ || + expr.operator === 44 /* MinusMinusToken */; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; function isExpressionKind(kind) { return kind === 195 /* ConditionalExpression */ || kind === 197 /* YieldExpression */ @@ -11824,9 +11780,19 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 207 /* Block */; + || isBlockStatement(node); } ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 207 /* Block */) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 224 /* TryStatement */ || node.parent.kind === 260 /* CatchClause */) { + return false; + } + } + return !ts.isFunctionBlock(node); + } // Module references /* @internal */ function isModuleReference(node) { @@ -14207,11 +14173,31 @@ var ts; var node = parseTokenNode(); return token() === 23 /* DotToken */ ? undefined : node; } - function parseLiteralTypeNode() { + function parseLiteralTypeNode(negative) { var node = createNode(173 /* LiteralType */); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(192 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 38 /* MinusToken */; + nextToken(); + } + var expression; + switch (token()) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + expression = parseLiteralLikeNode(token()); + break; + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + expression = parseTokenNode(); + } + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); } function nextTokenIsNumericLiteral() { return nextToken() === 8 /* NumericLiteral */; @@ -14244,7 +14230,7 @@ var ts; case 86 /* FalseKeyword */: return parseLiteralTypeNode(); case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); case 105 /* VoidKeyword */: case 95 /* NullKeyword */: return parseTokenNode(); @@ -14293,6 +14279,7 @@ var ts; case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 134 /* ObjectKeyword */: + case 39 /* AsteriskToken */: return true; case 38 /* MinusToken */: return lookAhead(nextTokenIsNumericLiteral); @@ -14721,7 +14708,7 @@ var ts; // Didn't appear to actually be a parenthesized arrow function. Just bail out. return undefined; } - var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256 /* Async */); + var isAsync = ts.hasModifier(arrowFunction, 256 /* Async */); // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. var lastToken = token(); @@ -14879,7 +14866,7 @@ var ts; function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(187 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); - var isAsync = (ts.getModifierFlags(node) & 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -15890,7 +15877,7 @@ var ts; parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; - var isAsync = (ts.getModifierFlags(node) & 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -16132,10 +16119,14 @@ var ts; function parseCatchClause() { var result = createNode(260 /* CatchClause */); parseExpected(74 /* CatchKeyword */); - if (parseExpected(19 /* OpenParenToken */)) { + if (parseOptional(19 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); + parseExpected(20 /* CloseParenToken */); + } + else { + // Keep shape of node to avoid degrading performance. + result.variableDeclaration = undefined; } - parseExpected(20 /* CloseParenToken */); result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); return finishNode(result); } @@ -17036,8 +17027,8 @@ var ts; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; - if (identifier || - token() === 39 /* AsteriskToken */ || + if (identifier || // import id + token() === 39 /* AsteriskToken */ || // import * token() === 17 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(140 /* FromKeyword */); @@ -17345,7 +17336,7 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseIsolatedJSDocComment(content, start, length) { initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); - sourceFile = { languageVariant: 0 /* Standard */, text: content }; + sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); @@ -18093,8 +18084,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -18231,8 +18222,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -19201,40 +19192,23 @@ var ts; return antecedent; } setFlowNodeReferenced(antecedent); - return { - flags: flags, - expression: expression, - antecedent: antecedent - }; + return { flags: flags, expression: expression, antecedent: antecedent }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); - return { - flags: 128 /* SwitchClause */, - switchStatement: switchStatement, - clauseStart: clauseStart, - clauseEnd: clauseEnd, - antecedent: antecedent - }; + return { flags: 128 /* SwitchClause */, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { setFlowNodeReferenced(antecedent); - return { - flags: 16 /* Assignment */, - antecedent: antecedent, - node: node - }; + return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; } function createFlowArrayMutation(antecedent, node) { setFlowNodeReferenced(antecedent); - return { - flags: 256 /* ArrayMutation */, - antecedent: antecedent, - node: node - }; + var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; + return res; } function finishFlowLabel(flow) { var antecedents = flow.antecedents; @@ -20956,7 +20930,6 @@ var ts; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); var name = node.name; var initializer = node.initializer; var dotDotDotToken = node.dotDotDotToken; @@ -20969,7 +20942,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. - if (modifierFlags & 92 /* ParameterPropertyModifier */) { + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; } // parameters with object rest destructuring are ES Next syntax @@ -21006,8 +20979,7 @@ var ts; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 2 /* Ambient */) { + if (ts.hasModifier(node, 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. transformFlags = 3 /* AssertTypeScript */; } @@ -21068,7 +21040,10 @@ var ts; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + if (!node.variableDeclaration) { + transformFlags |= 8 /* AssertESNext */; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -21283,10 +21258,9 @@ var ts; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; - var modifierFlags = ts.getModifierFlags(node); var declarationListTransformFlags = node.declarationList.transformFlags; // An ambient declaration is TypeScript syntax. - if (modifierFlags & 2 /* Ambient */) { + if (ts.hasModifier(node, 2 /* Ambient */)) { transformFlags = 3 /* AssertTypeScript */; } else { @@ -21634,6 +21608,176 @@ var ts; ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); } })(ts || (ts = {})); +/** @internal */ +var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = ts.createMap(); // Key is id as string + var visitedSymbols = ts.createMap(); // Key is id as string + return { + walkType: function (type) { + visitedTypes.clear(); + visitedSymbols.clear(); + visitType(type); + return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + }, + walkSymbol: function (symbol) { + visitedTypes.clear(); + visitedSymbols.clear(); + visitSymbol(symbol); + return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + }, + }; + function visitType(type) { + if (!type) { + return; + } + var typeIdString = type.id.toString(); + if (visitedTypes.has(typeIdString)) { + return; + } + visitedTypes.set(typeIdString, type); + // Reuse visitSymbol to visit the type's symbol, + // but be sure to bail on recuring into the type if accept declines the symbol. + var shouldBail = visitSymbol(type.symbol); + if (shouldBail) + return; + // Visit the type's related types, if any + if (type.flags & 32768 /* Object */) { + var objectType = type; + var objectFlags = objectType.objectFlags; + if (objectFlags & 4 /* Reference */) { + visitTypeReference(type); + } + if (objectFlags & 32 /* Mapped */) { + visitMappedType(type); + } + if (objectFlags & (1 /* Class */ | 2 /* Interface */)) { + visitInterfaceType(type); + } + if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) { + visitObjectType(objectType); + } + } + if (type.flags & 16384 /* TypeParameter */) { + visitTypeParameter(type); + } + if (type.flags & 196608 /* UnionOrIntersection */) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 262144 /* Index */) { + visitIndexType(type); + } + if (type.flags & 524288 /* IndexedAccess */) { + visitIndexedAccessType(type); + } + } + function visitTypeList(types) { + if (!types) { + return; + } + for (var i = 0; i < types.length; i++) { + visitType(types[i]); + } + } + function visitTypeReference(type) { + visitType(type.target); + visitTypeList(type.typeArguments); + } + function visitTypeParameter(type) { + visitType(getConstraintFromTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + visitTypeList(type.types); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + if (signature.typePredicate) { + visitType(signature.typePredicate.type); + } + visitTypeList(signature.typeParameters); + for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + visitTypeList(interfaceT.typeParameters); + visitTypeList(getBaseTypes(interfaceT)); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */); + visitType(stringIndexType); + var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */); + visitType(numberIndexType); + // The two checks above *should* have already resolved the type (if needed), so this should be cached + var resolved = resolveStructuredTypeMembers(type); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + visitSignature(signature); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + visitSignature(signature); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return; + } + var symbolIdString = ts.getSymbolId(symbol).toString(); + if (visitedSymbols.has(symbolIdString)) { + return; + } + visitedSymbols.set(symbolIdString, symbol); + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); // Should handle members on classes and such + if (symbol.flags & 1952 /* HasExports */) { + symbol.exports.forEach(visitSymbol); + } + ts.forEach(symbol.declarations, function (d) { + // Type queries are too far resolved when we just visit the symbol's type + // (their type resolved directly to the member deeply referenced) + // So to get the intervening symbols, we need to check if there's a type + // query node on any of the symbol's declarations and get symbols there + if (d.type && d.type.kind === 162 /* TypeQuery */) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); /// /// var ts; @@ -21647,6 +21791,12 @@ var ts; return compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(/*packageId*/ undefined, r); + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -21667,13 +21817,12 @@ var ts; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); + function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { if (!ts.hasProperty(jsonContent, fieldName)) { @@ -21778,7 +21927,9 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - resolved = realpath(resolved, host, traceEnabled); + if (!options.preserveSymlinks) { + resolved = realPath(resolved, host, traceEnabled); + } if (traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); } @@ -22182,7 +22333,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension }; + return { path: path_1, extension: extension, packageId: undefined }; } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -22209,7 +22360,7 @@ var ts; 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(", ")); + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } @@ -22235,17 +22386,24 @@ var ts; trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks) { + resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); - return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); + // Treat explicit "node_modules" import as an external library import. + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } } } - function realpath(path, host, traceEnabled) { + function realPath(path, host, traceEnabled) { if (!host.realpath) { return path; } @@ -22271,7 +22429,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return resolvedFromFile; + return noPackageId(resolvedFromFile); } } if (!onlyRecordFailures) { @@ -22291,6 +22449,9 @@ var ts; return !host.directoryExists || host.directoryExists(directoryName); } ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. @@ -22329,9 +22490,9 @@ var ts; case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); } - function tryExtension(extension) { - var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, extension: extension }; + function tryExtension(ext) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, ext: ext }; } } /** Return the file if it exists. */ @@ -22355,12 +22516,20 @@ var ts; function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + var packageId; if (considerPackageJson) { var packageJsonPath = pathToPackageJson(candidate); if (directoryExists && state.host.fileExists(packageJsonPath)) { - var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var jsonContent = readJson(packageJsonPath, state.host); + if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { + packageId = { name: jsonContent.name, version: jsonContent.version }; + } + var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); if (fromPackageJson) { - return fromPackageJson; + return withPackageId(packageId, fromPackageJson); } } else { @@ -22371,13 +22540,10 @@ var ts; failedLookupLocations.push(packageJsonPath); } } - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } - function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); if (!file) { return undefined; } @@ -22395,12 +22561,17 @@ var ts; // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); + var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); + if (result) { + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + ts.Debug.assert(result.packageId === undefined); + return { path: result.path, ext: result.extension }; + } } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { - var extension = ts.tryGetExtensionFromPath(path); - return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; } /** True if `extension` is one of the supported `extensions`. */ function extensionIsOk(extensions, extension) { @@ -22418,7 +22589,7 @@ var ts; } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { @@ -22497,7 +22668,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); } - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -22508,7 +22679,7 @@ var ts; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -22521,7 +22692,7 @@ var ts; return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; @@ -22533,7 +22704,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); } } } @@ -22578,6 +22749,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /* @internal */ var ts; (function (ts) { @@ -22705,6 +22877,9 @@ var ts; node = ts.getParseTreeNode(node, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, + getExportSymbolOfSymbol: function (symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, getTypeAtLocation: function (node) { node = ts.getParseTreeNode(node); return node ? getTypeOfNode(node) : unknownType; @@ -22767,6 +22942,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); @@ -22789,11 +22965,10 @@ var ts; getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, getBaseConstraintOfType: getBaseConstraintOfType, - getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, - resolveNameAtLocation: function (location, name, meaning) { - location = ts.getParseTreeNode(location); - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, ts.escapeLeadingUnderscores(name)); + resolveName: function (name, location, meaning) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); }, + getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -23324,12 +23499,17 @@ var ts; // 2. inside a function // 3. inside an instance property initializer, a reference to a non-instance property // 4. inside a static property initializer, a reference to a static method in the same class + // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) // or if usage is in a type context: // 1. inside a type query (typeof in type position) - if (usage.parent.kind === 246 /* ExportSpecifier */) { + if (usage.parent.kind === 246 /* ExportSpecifier */ || (usage.parent.kind === 243 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } + // When resolving symbols for exports, the `usage` location passed in can be the export site directly + if (usage.kind === 243 /* ExportAssignment */ && usage.isExportEquals) { + return true; + } var container = ts.getEnclosingBlockScopeContainer(declaration); return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { @@ -23360,13 +23540,13 @@ var ts; current.parent.kind === 149 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { - if (ts.getModifierFlags(current.parent) & 32 /* Static */) { + if (ts.hasModifier(current.parent, 32 /* Static */)) { if (declaration.kind === 151 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 149 /* PropertyDeclaration */ && !(ts.getModifierFlags(declaration) & 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 149 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -23480,7 +23660,7 @@ var ts; // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -23499,7 +23679,7 @@ var ts; result = undefined; break; } - if (lastLocation && ts.getModifierFlags(lastLocation) & 32 /* Static */) { + if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type // parameter list is associated, with the exception of static member declarations in classes. @@ -23516,6 +23696,18 @@ var ts; } } break; + case 201 /* ExpressionWithTypeArguments */: + // The type parameters of a class are not in scope in the base class expression. + if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { + var container = location.parent.parent; + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 793064 /* Type */))) { + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return undefined; + } + } + break; // It is not legal to reference a class's own type parameters from a computed property name that // belongs to the class. For example: // @@ -23585,7 +23777,10 @@ var ts; lastLocation = location; location = location.parent; } - if (result && nameNotFoundMessage && noUnusedIdentifiers) { + // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. + // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. + // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. + if (result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { result.isReferenced = true; } if (!result) { @@ -23684,7 +23879,7 @@ var ts; } // No static member is present. // Check if we're in an instance method and look for a relevant instance member. - if (location === container && !(ts.getModifierFlags(location) & 32 /* Static */)) { + if (location === container && !ts.hasModifier(location, 32 /* Static */)) { var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); @@ -24130,7 +24325,6 @@ var ts; if (ambientModule) { return ambientModule; } - var isRelative = ts.isExternalModuleNameRelative(moduleReference); var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); @@ -24152,7 +24346,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule && resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -24186,7 +24380,7 @@ var ts; // An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, // and an external module with no 'export =' declaration resolves to the module itself. function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias)) || moduleSymbol; } // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may @@ -24199,7 +24393,7 @@ var ts; return symbol; } function hasExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports.get("export=") !== undefined; + return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; } function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); @@ -24461,7 +24655,7 @@ var ts; if (symbolFromSymbolTable.flags & 2097152 /* Alias */ && symbolFromSymbolTable.escapedName !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) { - if (!useOnlyExternalAliasing || + if (!useOnlyExternalAliasing || // We can use any type of alias to get the name // Is this external alias, then use it to name ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); @@ -24526,6 +24720,10 @@ var ts; } return false; } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -24608,7 +24806,7 @@ var ts; // because these kind of aliases can be used to name types in declaration file var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(ts.getModifierFlags(anyImportSyntax) & 1 /* Export */) && + !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export isDeclarationVisible(anyImportSyntax.parent)) { // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time @@ -24817,8 +25015,7 @@ var ts; // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (!inTypeAlias && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); @@ -24900,10 +25097,10 @@ var ts; return createTypeNodeFromObjectType(type); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || + (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; })); @@ -24914,10 +25111,8 @@ var ts; } } function createTypeNodeFromObjectType(type) { - if (type.objectFlags & 32 /* Mapped */) { - if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { - return createMappedTypeNodeFromType(type); - } + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -25505,7 +25700,7 @@ var ts; buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } else if (!(flags & 1024 /* InTypeAlias */) && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + ((flags & 65536 /* UseAliasDefinedOutsideCurrentScope */) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); } @@ -25667,9 +25862,7 @@ var ts; if (!symbolStack) { symbolStack = []; } - var isConstructorObject = type.flags & 32768 /* Object */ && - getObjectFlags(type) & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & 32 /* Class */; + var isConstructorObject = type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; if (isConstructorObject) { writeLiteralType(type, flags); } @@ -25685,17 +25878,17 @@ var ts; writeLiteralType(type, flags); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { + (symbol.parent || // is exported function symbol + ts.some(symbol.declarations, function (declaration) { return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return !!(flags & 4 /* UseTypeOfFunction */) || - (ts.contains(symbolStack, symbol)); // it is type of the symbol uses itself recursively + return !!(flags & 4 /* UseTypeOfFunction */) || // use typeof if format flags specify it + ts.contains(symbolStack, symbol); // it is type of the symbol uses itself recursively } } } @@ -25733,11 +25926,9 @@ var ts; return false; } function writeLiteralType(type, flags) { - if (type.objectFlags & 32 /* Mapped */) { - if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { - writeMappedType(type); - return; - } + if (isGenericMappedType(type)) { + writeMappedType(type); + return; } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -26113,7 +26304,7 @@ var ts; case 154 /* SetAccessor */: case 151 /* MethodDeclaration */: case 150 /* MethodSignature */: - if (ts.getModifierFlags(node) & (8 /* Private */ | 16 /* Protected */)) { + if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } @@ -26910,8 +27101,8 @@ var ts; // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set // in-place and returns the same array. function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; @@ -27055,7 +27246,7 @@ var ts; return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + type.resolvedBaseTypes = ts.emptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); if (!(baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 1 /* Any */))) { return; @@ -27104,12 +27295,7 @@ var ts; error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); return; } - if (type.resolvedBaseTypes === ts.emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } + type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type) { // An unapplied type parameter has its symbol still the same as the matching argument symbol. @@ -27221,7 +27407,9 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var declaration = ts.findDeclaration(symbol, function (d) { return d.kind === 283 /* JSDocTypedefTag */ || d.kind === 231 /* TypeAliasDeclaration */; }); + var declaration = ts.find(symbol.declarations, function (d) { + return d.kind === 283 /* JSDocTypedefTag */ || d.kind === 231 /* TypeAliasDeclaration */; + }); var type = getTypeFromTypeNode(declaration.kind === 283 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type); if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -27753,17 +27941,12 @@ var ts; else { // Combinations of function, class, enum and module var members = emptySymbols; - var constructSignatures = ts.emptyArray; var stringIndexInfo = undefined; if (symbol.exports) { members = getExportsOfSymbol(symbol); } if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); - constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); - if (!constructSignatures.length) { - constructSignatures = getDefaultConstructSignatures(classType); - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 540672 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); @@ -27774,7 +27957,7 @@ var ts; } } var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; - setStructuredTypeMembers(type, members, ts.emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); // We resolve the members before computing the signatures because a signature may use // typeof with a qualified name expression that circularly references the type we are // in the process of resolving (see issue #6072). The temporarily empty signature list @@ -27782,6 +27965,15 @@ var ts; if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); } + // And likewise for construct signatures for classes + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } } } /** Resolve the members of a mapped type { [P in K]: T } */ @@ -27883,8 +28075,7 @@ var ts; return getObjectFlags(type) & 32 /* Mapped */ && !!type.declaration.questionToken; } function isGenericMappedType(type) { - return getObjectFlags(type) & 32 /* Mapped */ && - maybeTypeOfKind(getConstraintTypeFromMappedType(type), 540672 /* TypeVariable */ | 262144 /* Index */); + return getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -27990,6 +28181,10 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + var transformed = getTransformedIndexedAccessType(type); + if (transformed) { + return transformed; + } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; @@ -28057,11 +28252,18 @@ var ts; return stringType; } if (t.flags & 524288 /* IndexedAccess */) { + var transformed = getTransformedIndexedAccessType(t); + if (transformed) { + return getBaseConstraint(transformed); + } var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; } + if (isGenericMappedType(t)) { + return emptyObjectType; + } return t; } } @@ -28608,6 +28810,9 @@ var ts; } return signature.resolvedReturnType; } + function isResolvingReturnTypeOfSignature(signature) { + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); @@ -28680,7 +28885,7 @@ var ts; function getIndexInfoOfSymbol(symbol, kind) { var declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64 /* Readonly */) !== 0, declaration); + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration); } return undefined; } @@ -28978,8 +29183,8 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; switch (declaration.kind) { case 229 /* ClassDeclaration */: case 230 /* InterfaceDeclaration */: @@ -29475,17 +29680,16 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { + if (!(indexType.flags & 6144 /* Nullable */) && isTypeAssignableToKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); - return unknownType; } return indexInfo.type; } @@ -29517,35 +29721,84 @@ var ts; return anyType; } function getIndexedAccessForMappedType(type, indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - return unknownType; + if (accessNode) { + // Check if the index type is assignable to 'keyof T' for the object type. + if (!isTypeAssignableTo(indexType, getIndexType(type))) { + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(type)); + return unknownType; + } + if (accessNode.kind === 180 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && type.declaration.readonlyToken) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + } } var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); } + function isGenericObjectType(type) { + return type.flags & 540672 /* TypeVariable */ ? true : + getObjectFlags(type) & 32 /* Mapped */ ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : + type.flags & 196608 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericObjectType) : + false; + } + function isGenericIndexType(type) { + return type.flags & (540672 /* TypeVariable */ | 262144 /* Index */) ? true : + type.flags & 196608 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericIndexType) : + false; + } + // Return true if the given type is a non-generic object type with a string index signature and no + // other members. + function isStringIndexOnlyType(type) { + if (type.flags & 32768 /* Object */ && !isGenericMappedType(type)) { + var t = resolveStructuredTypeMembers(type); + return t.properties.length === 0 && + t.callSignatures.length === 0 && t.constructSignatures.length === 0 && + t.stringIndexInfo && !t.numberIndexInfo; + } + return false; + } + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. + function getTransformedIndexedAccessType(type) { + var objectType = type.objectType; + if (objectType.flags & 131072 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); + } + else { + regularTypes.push(t); + } + } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + return undefined; + } function getIndexedAccessType(objectType, indexType, accessNode) { - // If the index type is generic, if the object type is generic and doesn't originate in an expression, - // or if the object type is a mapped type with a generic constraint, we are performing a higher-order - // index access where we cannot meaningfully access the properties of the object type. Note that for a - // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to - // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved - // eagerly using the constraint type of 'this' at the given location. - if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || - maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) || - isGenericMappedType(objectType)) { + // If the object type is a mapped type { [P in K]: E }, where K is generic, we instantiate E using a mapper + // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we + // construct the type Box. + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + // Otherwise, if the index type is generic, or if the object type is generic and doesn't originate in an + // expression, we are performing a higher-order index access where we cannot meaningfully access the properties + // of the object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates + // in an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' + // has always been resolved eagerly using the constraint type of 'this' at the given location. + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { if (objectType.flags & 1 /* Any */) { return objectType; } - // If the object type is a mapped type { [P in K]: E }, we instantiate E using a mapper that substitutes - // the index type for P. For example, for an index access { [P in K]: Box }[X], we construct the - // type Box. - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } - // Otherwise we defer the operation by creating an indexed access type. + // Defer the operation by creating an indexed access type. var id = objectType.id + "," + indexType.id; var type = indexedAccessTypes.get(id); if (!type) { @@ -29759,7 +30012,7 @@ var ts; var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 230 /* InterfaceDeclaration */)) { - if (!(ts.getModifierFlags(container) & 32 /* Static */) && + if (!ts.hasModifier(container, 32 /* Static */) && (container.kind !== 152 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } @@ -29912,7 +30165,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.inferences) : + createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function identityMapper(type) { @@ -30222,16 +30475,16 @@ var ts; if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - // For arrow functions we now know we're not context sensitive. - if (node.kind === 187 /* ArrowFunction */) { - return false; + if (node.kind !== 187 /* ArrowFunction */) { + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. + var parameter = ts.firstOrUndefined(node.parameters); + if (!(parameter && ts.parameterIsThisKeyword(parameter))) { + return true; + } } - // If the first parameter is not an explicit 'this' parameter, then the function has - // an implicit 'this' parameter which is subject to contextual typing. Otherwise we - // know that all parameters (including 'this') have type annotations and nothing is - // subject to contextual typing. - var parameter = ts.firstOrUndefined(node.parameters); - return !(parameter && ts.parameterIsThisKeyword(parameter)); + // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. + return node.body.kind === 207 /* Block */ ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); @@ -30317,7 +30570,7 @@ var ts; return 0 /* False */; } if (source.typeParameters) { - source = instantiateSignatureInContextOf(source, target); + source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); @@ -30376,7 +30629,7 @@ var ts; // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions if (target.typePredicate) { if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(target.typePredicate)) { if (reportErrors) { @@ -30395,7 +30648,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -30404,11 +30657,13 @@ var ts; return 0 /* False */; } if (source.kind === 1 /* Identifier */) { - var sourceIdentifierPredicate = source; - var targetIdentifierPredicate = target; - if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + var sourcePredicate = source; + var targetPredicate = target; + var sourceIndex = sourcePredicate.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); + var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); + if (sourceIndex !== targetIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourcePredicate.parameterName, targetPredicate.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0 /* False */; @@ -30560,8 +30815,7 @@ var ts; return true; } if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); + var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1 /* Succeeded */; } @@ -30697,11 +30951,21 @@ var ts; !(target.flags & 65536 /* Union */) && !isIntersectionConstituent && source !== globalObjectType && - getPropertiesOfType(source).length > 0 && + (getPropertiesOfType(source).length > 0 || + getSignaturesOfType(source, 0 /* Call */).length > 0 || + getSignaturesOfType(source, 1 /* Construct */).length > 0) && isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { - reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + var calls = getSignaturesOfType(source, 0 /* Call */); + var constructs = getSignaturesOfType(source, 1 /* Construct */); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } } return 0 /* False */; } @@ -30929,7 +31193,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var id = getRelationKey(source, target, relation); var related = relation.get(id); if (related !== undefined) { if (reportErrors && related === 2 /* Failed */) { @@ -31411,6 +31675,11 @@ var ts; if (sourceInfo) { return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); } + if (isGenericMappedType(source)) { + // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } + // if T is related to U. + return kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + } if (isObjectLiteralType(source)) { var related = -1 /* True */; if (kind === 0 /* String */) { @@ -31444,8 +31713,8 @@ var ts; if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; - var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */); // A public, protected and private signature is assignable to a private signature. if (targetAccessibility === 8 /* Private */) { return true; @@ -31464,6 +31733,50 @@ var ts; return false; } } + function isUnconstrainedTypeParameter(type) { + return type.flags & 16384 /* TypeParameter */ && !getConstraintFromTypeParameter(type); + } + function isTypeReferenceWithGenericArguments(type) { + return getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, isUnconstrainedTypeParameter); + } + /** + * getTypeReferenceId(A) returns "111=0-12=1" + * where A.id=111 and number.id=12 + */ + function getTypeReferenceId(type, typeParameters) { + var result = "" + type.target.id; + for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { + var t = _a[_i]; + if (isUnconstrainedTypeParameter(t)) { + var index = ts.indexOf(typeParameters, t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + } + else { + result += "-" + t.id; + } + } + return result; + } + /** + * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. + * For other cases, the types ids are used. + */ + function getRelationKey(source, target, relation) { + if (relation === identityRelation && source.id > target.id) { + var temp = source; + source = target; + target = temp; + } + if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { + var typeParameters = []; + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + } + return source.id + "," + target.id; + } // 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) { @@ -31509,7 +31822,7 @@ var ts; var symbol = type.symbol; if (symbol && symbol.flags & 32 /* Class */) { var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.getModifierFlags(declaration) & 128 /* Abstract */) { + if (declaration && ts.hasModifier(declaration, 128 /* Abstract */)) { return true; } } @@ -31960,13 +32273,14 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(signature, flags, baseInferences) { + function createInferenceContext(signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); var context = mapper; context.mappedTypes = signature.typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; + context.compareTypes = compareTypes || compareTypesAssignable; return context; function mapper(t) { for (var i = 0; i < inferences.length; i++) { @@ -32061,6 +32375,19 @@ var ts; return inference.candidates && getUnionType(inference.candidates, /*subtypeReduction*/ true); } } + function isPossiblyAssignableTo(source, target) { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + if (!(targetProp.flags & (16777216 /* Optional */ | 4194304 /* Prototype */))) { + var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (!sourceProp) { + return false; + } + } + } + return true; + } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; @@ -32257,15 +32584,19 @@ var ts; return; } } - inferFromProperties(source, target); - inferFromSignatures(source, target, 0 /* Call */); - inferFromSignatures(source, target, 1 /* Construct */); - inferFromIndexTypes(source, target); + // Infer from the members of source and target only if the two types are possibly related. We check + // in both directions because we may be inferring for a co-variant or a contra-variant position. + if (isPossiblyAssignableTo(source, target) || isPossiblyAssignableTo(target, source)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { - var targetProp = properties_5[_i]; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -32382,7 +32713,7 @@ var ts; var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { inference.inferredType = inferredType = instantiatedConstraint; } } @@ -32440,16 +32771,6 @@ var ts; } return undefined; } - function getLeftmostIdentifierOrThis(node) { - switch (node.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - return node; - case 179 /* PropertyAccessExpression */: - return getLeftmostIdentifierOrThis(node.expression); - } - return undefined; - } function getBindingElementNameText(element) { if (element.parent.kind === 174 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; @@ -32975,7 +33296,7 @@ var ts; parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -33143,7 +33464,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { + if (isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -33978,7 +34299,7 @@ var ts; break; case 149 /* PropertyDeclaration */: case 148 /* PropertySignature */: - if (ts.getModifierFlags(container) & 32 /* Static */) { + if (ts.hasModifier(container, 32 /* Static */)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } @@ -34081,7 +34402,7 @@ var ts; if (!isCallExpression && container.kind === 152 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } - if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { + if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { nodeCheckFlag = 512 /* SuperStatic */; } else { @@ -34144,7 +34465,7 @@ var ts; // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment // while a property access can. - if (container.kind === 151 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { + if (container.kind === 151 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -34202,7 +34523,7 @@ var ts; // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression if (ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */) { - if (ts.getModifierFlags(container) & 32 /* Static */) { + if (ts.hasModifier(container, 32 /* Static */)) { return container.kind === 151 /* MethodDeclaration */ || container.kind === 150 /* MethodSignature */ || container.kind === 153 /* GetAccessor */ || @@ -34414,7 +34735,7 @@ var ts; // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature // and that call signature is non-generic, return statements are contextually typed by the return type of the signature var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); - if (signature) { + if (signature && !isResolvingReturnTypeOfSignature(signature)) { return getReturnTypeOfSignature(signature); } return undefined; @@ -34543,12 +34864,12 @@ var ts; } if (ts.isJsxAttribute(node.parent)) { // JSX expression is in JSX attribute - return getTypeOfPropertyOfType(attributesType, node.parent.name.escapedText); + return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); } else if (node.parent.kind === 249 /* JsxElement */) { // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; + return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; } else { // JSX expression is in JSX spread attribute @@ -34564,7 +34885,7 @@ var ts; if (!attributesType || isTypeAny(attributesType)) { return undefined; } - return getTypeOfPropertyOfType(attributesType, attribute.name.escapedText); + return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { return attributesType; @@ -34832,10 +35153,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), 84 /* NumberLike */); - } - function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || isTypeOfKind(type, kind); + return isTypeAssignableToKind(checkComputedPropertyName(name), 84 /* NumberLike */); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -34870,7 +35188,9 @@ 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, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { + if (links.resolvedType.flags & 6144 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */) && + !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -35484,9 +35804,7 @@ var ts; * emptyObjectType if there is no "prop" in the element instance type */ function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (!elementType) { - elementType = checkExpression(openingLikeElement.tagName); - } + if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } if (elementType.flags & 65536 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { @@ -35607,11 +35925,12 @@ var ts; */ function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { + var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; + if (!links[linkLocation]) { var elemClassType = getJsxGlobalElementClassType(); - return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); } - return links.resolvedJsxElementAttributesType; + return links[linkLocation]; } /** * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. @@ -35933,9 +36252,12 @@ var ts; } var prop = getPropertyOfType(apparentType, right.escapedText); if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */); - if (stringIndexType) { - return stringIndexType; + var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); + if (indexInfo && indexInfo.type) { + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + return indexInfo.type; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); @@ -36084,7 +36406,7 @@ var ts; if (prop && noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { + prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } @@ -36407,8 +36729,8 @@ var ts; return undefined; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) - function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature, 1 /* InferUnionTypes */); + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + var context = createInferenceContext(signature, 1 /* InferUnionTypes */, compareTypes); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); @@ -36780,7 +37102,7 @@ var ts; return getLiteralType(element.name.text); case 144 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { + if (isTypeAssignableToKind(nameType, 512 /* ESSymbol */)) { return nameType; } else { @@ -36921,9 +37243,10 @@ var ts; // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. + var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; var excludeArgument; var excludeCount = 0; - if (!isDecorator) { + if (!isDecorator && !isSingleNonGenericCandidate) { // We do not need to call `getEffectiveArgumentCount` here as it only // applies when calculating the number of arguments for a decorator. for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { @@ -37068,6 +37391,17 @@ var ts; if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; candidateForTypeArgumentError = undefined; + if (isSingleNonGenericCandidate) { + var candidate = candidates[0]; + if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + return undefined; + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = candidate; + return undefined; + } + return candidate; + } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { @@ -37230,7 +37564,7 @@ var ts; // In the case of a merged class-module or class-interface declaration, // 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 */) { + if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } @@ -37277,9 +37611,9 @@ var ts; return true; } var declaration = signature.declaration; - var modifiers = ts.getModifierFlags(declaration); + var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); // Public constructor is accessible. - if (!(modifiers & 24 /* NonPublicAccessibilityModifier */)) { + if (!modifiers) { return true; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -37488,7 +37822,7 @@ var ts; */ function checkCallExpression(node) { // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); + checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 97 /* SuperKeyword */) { return voidType; @@ -37528,7 +37862,7 @@ var ts; } function checkImportCallExpression(node) { // Check grammar of dynamic import - checkGrammarArguments(node, node.arguments) || checkGrammarImportCallExpression(node); + checkGrammarArguments(node.arguments) || checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } @@ -37546,11 +37880,33 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeOfSymbol(esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); } } return createPromiseReturnType(node, anyType); } + function getTypeWithSyntheticDefaultImportType(type, symbol) { + if (allowSyntheticDefaultImports && type && type !== unknownType) { + var synthType = type; + if (!synthType.syntheticType) { + if (!getPropertyOfType(type, "default" /* Default */)) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + anonymousSymbol.type = defaultContainingObject; + synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + } + else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } function isCommonJsRequire(node) { if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { return false; @@ -37675,15 +38031,15 @@ var ts; } // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push // the destructured type into the contained binding elements. - function assignBindingElementTypes(node) { - if (ts.isBindingPattern(node.name)) { - for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71 /* Identifier */) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); - } - assignBindingElementTypes(element); + function assignBindingElementTypes(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 71 /* Identifier */) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + else { + assignBindingElementTypes(element.name); } } } @@ -37692,13 +38048,14 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = contextualType; - 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 && - (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(name); + var decl = parameter.valueDeclaration; + if (decl.name.kind !== 71 /* Identifier */) { + // if inference didn't come up with anything but {}, fall back to the binding pattern if present. + if (links.type === emptyObjectType) { + links.type = getTypeFromBindingPattern(decl.name); + } + assignBindingElementTypes(decl.name); } - assignBindingElementTypes(parameter.valueDeclaration); } } function createPromiseType(promisedType) { @@ -37934,16 +38291,16 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - // Grammar checking - var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186 /* FunctionExpression */) { - checkGrammarForGenerator(node); - } // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { checkNodeDeferred(node); return anyFunctionType; } + // Grammar checking + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 186 /* FunctionExpression */) { + checkGrammarForGenerator(node); + } var links = getNodeLinks(node); var type = getTypeOfSymbol(node.symbol); // Check if function expression is contextually typed and assign parameter types if so. @@ -38028,7 +38385,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { + if (!isTypeAssignableToKind(type, 84 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -38129,8 +38486,13 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + if (node.operand.kind === 8 /* NumericLiteral */) { + if (node.operator === 38 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + } + else if (node.operator === 37 /* PlusToken */) { + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } } switch (node.operator) { case 37 /* PlusToken */: @@ -38186,33 +38548,22 @@ var ts; } return false; } - // Return true if type is of the given kind. A union type is of a given kind if all constituent types - // are of the given kind. An intersection type is of a given kind if at least one constituent type is - // of the given kind. - function isTypeOfKind(type, kind) { - if (type.flags & kind) { + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { return true; } - if (type.flags & 65536 /* Union */) { - var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; - if (!isTypeOfKind(t, kind)) { - return false; - } - } - return true; + if (strict && source.flags & (1 /* Any */ | 1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */)) { + return false; } - if (type.flags & 131072 /* Intersection */) { - var types = type.types; - for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { - var t = types_19[_a]; - if (isTypeOfKind(t, kind)) { - return true; - } - } - } - return false; + return (kind & 84 /* NumberLike */ && isTypeAssignableTo(source, numberType)) || + (kind & 262178 /* StringLike */ && isTypeAssignableTo(source, stringType)) || + (kind & 136 /* BooleanLike */ && isTypeAssignableTo(source, booleanType)) || + (kind & 1024 /* Void */ && isTypeAssignableTo(source, voidType)) || + (kind & 8192 /* Never */ && isTypeAssignableTo(source, neverType)) || + (kind & 4096 /* Null */ && isTypeAssignableTo(source, nullType)) || + (kind & 2048 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || + (kind & 512 /* ESSymbol */ && isTypeAssignableTo(source, esSymbolType)) || + (kind & 16777216 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); } function isConstEnumObjectType(type) { return getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); @@ -38229,7 +38580,7 @@ var ts; // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. // The result is always of the Boolean primitive type. // NOTE: do not raise error if leftType is unknown as related error was already reported - if (isTypeOfKind(leftType, 8190 /* Primitive */)) { + if (!isTypeAny(leftType) && isTypeAssignableToKind(leftType, 8190 /* Primitive */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported @@ -38251,18 +38602,18 @@ 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, 84 /* NumberLike */ | 512 /* ESSymbol */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(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 */)) { + if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 540672 /* TypeVariable */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var p = properties_6[_i]; + for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { + var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); } return sourceType; @@ -38541,30 +38892,28 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeOfKind(leftType, 1 /* Any */ | 262178 /* StringLike */) && !isTypeOfKind(rightType, 1 /* Any */ | 262178 /* StringLike */)) { + if (!isTypeAssignableToKind(leftType, 262178 /* StringLike */) && !isTypeAssignableToKind(rightType, 262178 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 84 /* NumberLike */) && isTypeOfKind(rightType, 84 /* NumberLike */)) { + if (isTypeAssignableToKind(leftType, 84 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 84 /* NumberLike */, /*strict*/ true)) { // 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; } - else { - if (isTypeOfKind(leftType, 262178 /* StringLike */) || isTypeOfKind(rightType, 262178 /* StringLike */)) { - // If one or both operands are of the String primitive type, the result is of the String primitive type. - resultType = stringType; - } - else if (isTypeAny(leftType) || isTypeAny(rightType)) { - // Otherwise, the result is of type Any. - // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. - resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; - } - // Symbols are not allowed at all in arithmetic expressions - if (resultType && !checkForDisallowedESSymbolOperand(operator)) { - return resultType; - } + else if (isTypeAssignableToKind(leftType, 262178 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 262178 /* StringLike */, /*strict*/ true)) { + // If one or both operands are of the String primitive type, the result is of the String primitive type. + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + // Otherwise, the result is of type Any. + // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; + } + // Symbols are not allowed at all in arithmetic expressions + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; } if (!resultType) { reportOperatorError(); @@ -38749,13 +39098,12 @@ var ts; return getBestChoiceType(type1, type2); } function checkLiteralExpression(node) { - if (node.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(node); - } switch (node.kind) { + case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101 /* TrueKeyword */: return trueType; @@ -38951,6 +39299,7 @@ var ts; return checkSuperExpression(node); case 95 /* NullKeyword */: return nullWideningType; + case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: case 101 /* TrueKeyword */: @@ -38958,8 +39307,6 @@ var ts; return checkLiteralExpression(node); case 196 /* TemplateExpression */: return checkTemplateExpression(node); - case 13 /* NoSubstitutionTemplateLiteral */: - return stringType; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 177 /* ArrayLiteralExpression */: @@ -39058,7 +39405,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.getModifierFlags(node) & 92 /* ParameterPropertyModifier */) { + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { func = ts.getContainingFunction(node); if (!(func.kind === 152 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -39264,7 +39611,7 @@ var ts; } } else { - var isStatic = ts.getModifierFlags(member) & 32 /* Static */; + var isStatic = ts.hasModifier(member, 32 /* Static */); var names = isStatic ? staticNames : instanceNames; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { @@ -39320,7 +39667,7 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; var memberNameNode = member.name; - var isStatic = ts.getModifierFlags(member) & 32 /* Static */; + var isStatic = ts.hasModifier(member, 32 /* Static */); if (isStatic && memberNameNode) { var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); switch (memberName) { @@ -39418,7 +39765,7 @@ var ts; checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.getModifierFlags(node) & 128 /* Abstract */ && node.body) { + if (ts.hasModifier(node, 128 /* Abstract */) && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -39458,17 +39805,9 @@ var ts; } return ts.forEachChild(n, containsSuperCall); } - function markThisReferencesAsErrors(n) { - if (n.kind === 99 /* ThisKeyword */) { - error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - } - else if (n.kind !== 186 /* FunctionExpression */ && n.kind !== 228 /* FunctionDeclaration */) { - ts.forEachChild(n, markThisReferencesAsErrors); - } - } function isInstancePropertyWithInitializer(n) { return n.kind === 149 /* PropertyDeclaration */ && - !(ts.getModifierFlags(n) & 32 /* Static */) && + !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } // TS 1.0 spec (April 2014): 8.3.2 @@ -39488,8 +39827,8 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92 /* ParameterPropertyModifier */; }); + var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -39540,10 +39879,12 @@ var ts; var otherKind = node.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if ((ts.getModifierFlags(node) & 28 /* AccessibilityModifier */) !== (ts.getModifierFlags(otherAccessor) & 28 /* AccessibilityModifier */)) { + var nodeFlags = ts.getModifierFlags(node); + var otherFlags = ts.getModifierFlags(otherAccessor); + if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if (ts.hasModifier(node, 128 /* Abstract */) !== ts.hasModifier(otherAccessor, 128 /* Abstract */)) { + if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } // TypeScript 1.0 spec (April 2014): 4.5 @@ -39591,7 +39932,7 @@ var ts; function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); if (node.kind === 159 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { - grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); if (type !== unknownType) { @@ -39600,7 +39941,17 @@ var ts; ts.forEach(node.typeArguments, checkSourceElement); if (produceDiagnostics) { var symbol = getNodeLinks(node).resolvedSymbol; - var typeParameters = symbol.flags & 524288 /* TypeAlias */ ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; + if (!symbol) { + // There is no resolved symbol cached if the type resolved to a builtin + // via JSDoc type reference resolution (eg, Boolean became boolean), none + // of which are generic when they have no associated symbol + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return; + } + var typeParameters = symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters; + if (!typeParameters && getObjectFlags(type) & 4 /* Reference */) { + typeParameters = type.target.localTypeParameters; + } checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } @@ -39645,18 +39996,17 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - // 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, 84 /* NumberLike */)) { - var constraint = getBaseConstraintOfType(objectType); - if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { - return type; - } + // Check if we're indexing with a numeric type and if either object or index types + // is a generic type with a constraint that has a numeric index signature. + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { + return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); return type; } function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } function checkMappedType(node) { @@ -39667,7 +40017,7 @@ var ts; checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); } function isPrivateWithinAmbient(node) { - return (ts.getModifierFlags(node) & 8 /* Private */) && ts.isInAmbientContext(node); + return ts.hasModifier(node, 8 /* Private */) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); @@ -39767,13 +40117,13 @@ var ts; (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { var reportError = (node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */) && - (ts.getModifierFlags(node) & 32 /* Static */) !== (ts.getModifierFlags(subsequentNode) & 32 /* Static */); + ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members // 2. something with the same name was defined before the set of overloads that prevents them from merging // here we'll report error only for the first case since for second we should already report error in binder if (reportError) { - var diagnostic = ts.getModifierFlags(node) & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -39791,7 +40141,7 @@ var ts; else { // Report different errors regarding non-consecutive blocks of declarations depending on whether // the node in question is abstract. - if (ts.getModifierFlags(node) & 128 /* Abstract */) { + if (ts.hasModifier(node, 128 /* Abstract */)) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -39801,8 +40151,8 @@ var ts; } var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var current = declarations_5[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); var inAmbientContextOrInterface = node.parent.kind === 230 /* InterfaceDeclaration */ || node.parent.kind === 163 /* TypeLiteral */ || inAmbientContext; @@ -39859,7 +40209,7 @@ var ts; } // Abstract methods can't have an implementation -- in particular, they don't need one. if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -40426,7 +40776,7 @@ var ts; // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. var firstDeclaration = ts.find(localSymbol.declarations, // Get first non javascript function declaration - function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)); }); + function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536 /* JavaScriptFile */); }); // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); @@ -40569,14 +40919,14 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 151 /* MethodDeclaration */ || member.kind === 149 /* PropertyDeclaration */) { - if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8 /* Private */) { + if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); } } else if (member.kind === 152 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8 /* Private */) { + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); } } @@ -40997,7 +41347,7 @@ var ts; 128 /* Abstract */ | 64 /* Readonly */ | 32 /* Static */; - return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); + return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); @@ -41162,7 +41512,7 @@ var ts; } // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { + if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 540672 /* TypeVariable */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -41662,7 +42012,7 @@ var ts; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!(ts.getModifierFlags(member) & 32 /* Static */) && ts.hasDynamicName(member)) { + if (!ts.hasModifier(member, 32 /* Static */) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); @@ -41773,8 +42123,8 @@ var ts; if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { // Report an error on every conflicting declaration. var name = symbolToString(symbol); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } @@ -41783,8 +42133,8 @@ var ts; function areTypeParametersIdentical(declarations, typeParameters) { var maxTypeArgumentCount = ts.length(typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; // If this declaration has too few or too many type parameters, we report an error var numTypeParameters = ts.length(declaration.typeParameters); if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { @@ -41827,7 +42177,7 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (!node.name && !(ts.getModifierFlags(node) & 512 /* Default */)) { + if (!node.name && !ts.hasModifier(node, 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -41925,7 +42275,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { var declaration = signatures[0].declaration; - if (declaration && ts.getModifierFlags(declaration) & 8 /* Private */) { + if (declaration && ts.hasModifier(declaration, 8 /* Private */)) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); @@ -41981,7 +42331,7 @@ var ts; // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. - if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128 /* Abstract */))) { + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { if (derivedClassDecl.kind === 199 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -42032,8 +42382,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { - var prop = properties_7[_a]; + for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { + var prop = properties_8[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -42307,8 +42657,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; if ((declaration.kind === 229 /* ClassDeclaration */ || (declaration.kind === 228 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { @@ -42558,7 +42908,7 @@ var ts; // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -42586,7 +42936,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (ts.getModifierFlags(node) & 1 /* Export */) { + if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -42617,7 +42967,7 @@ var ts; // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -42682,7 +43032,7 @@ var ts; return; } // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 71 /* Identifier */) { @@ -42736,8 +43086,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -43046,7 +43396,7 @@ var ts; return []; } var symbols = ts.createSymbolTable(); - var memberFlags = 0 /* None */; + var isStatic = false; populateSymbols(); return symbolsToArray(symbols); function populateSymbols() { @@ -43075,7 +43425,7 @@ var ts; // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. - if (!(memberFlags & 32 /* Static */)) { + if (!isStatic) { copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); } break; @@ -43089,7 +43439,7 @@ var ts; if (ts.introducesArgumentsExoticObject(location)) { copySymbol(argumentsSymbol, meaning); } - memberFlags = ts.getModifierFlags(location); + isStatic = ts.hasModifier(location, 32 /* Static */); location = location.parent; } copySymbols(globals, meaning); @@ -43351,12 +43701,7 @@ var ts; // index access if (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { var objectType = getTypeOfExpression(node.parent.expression); - if (objectType === unknownType) - return undefined; - var apparentType = getApparentType(objectType); - if (apparentType === unknownType) - return undefined; - return getPropertyOfType(apparentType, node.text); + return getPropertyOfType(objectType, node.text); } break; } @@ -43487,7 +43832,7 @@ var ts; */ function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return ts.getModifierFlags(node) & 32 /* Static */ + return ts.hasModifier(node, 32 /* Static */) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -43769,13 +44114,13 @@ var ts; return strictNullChecks && !isOptionalParameter(parameter) && parameter.initializer && - !(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - !!(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function getNodeCheckFlags(node) { return getNodeLinks(node).flags; @@ -43835,22 +44180,22 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { + else if (isTypeAssignableToKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeOfKind(type, 136 /* BooleanLike */)) { + else if (isTypeAssignableToKind(type, 136 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 84 /* NumberLike */)) { + else if (isTypeAssignableToKind(type, 84 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 262178 /* StringLike */)) { + else if (isTypeAssignableToKind(type, 262178 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 512 /* ESSymbol */)) { + else if (isTypeAssignableToKind(type, 512 /* ESSymbol */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -44346,7 +44691,7 @@ var ts; node.kind !== 154 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 229 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { + if (!(node.parent.kind === 229 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -44469,8 +44814,7 @@ var ts; if (list && list.hasTrailingComma) { var start = list.end - ",".length; var end = list.end; - var sourceFile = ts.getSourceFileOfNode(list[0]); - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + return grammarErrorAtPos(list[0], start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); } } function checkGrammarTypeParameterList(typeParameters, file) { @@ -44547,7 +44891,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (ts.getModifierFlags(parameter) !== 0) { + if (ts.hasModifiers(parameter)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -44582,19 +44926,18 @@ var ts; return checkGrammarForDisallowedTrailingComma(typeArguments) || checkGrammarForAtLeastOneTypeArgument(node, typeArguments); } - function checkGrammarForOmittedArgument(node, args) { + function checkGrammarForOmittedArgument(args) { if (args) { - var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; if (arg.kind === 200 /* OmittedExpression */) { - return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } } } - function checkGrammarArguments(node, args) { - return checkGrammarForOmittedArgument(node, args); + function checkGrammarArguments(args) { + return checkGrammarForOmittedArgument(args); } function checkGrammarHeritageClause(node) { var types = node.types; @@ -44603,8 +44946,7 @@ var ts; } if (types && types.length === 0) { var listType = ts.tokenToString(node.token); - var sourceFile = ts.getSourceFileOfNode(node); - return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } return ts.forEach(types, checkGrammarExpressionWithTypeArguments); } @@ -44850,10 +45192,10 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128 /* Abstract */)) { - return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } - else if (accessor.body && ts.getModifierFlags(accessor) & 128 /* Abstract */) { + else if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) { return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); } else if (accessor.typeParameters) { @@ -44910,7 +45252,7 @@ var ts; return true; } else if (node.body === undefined) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } if (ts.isClassLike(node.parent)) { @@ -44991,7 +45333,7 @@ var ts; } if (node.initializer) { // Error on equals token which immediately precedes the initializer - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } } } @@ -45012,13 +45354,13 @@ var ts; else { // Error on equals token which immediate precedes the initializer var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { // Error on equals token which immediate precedes the initializer var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } else if (!node.initializer) { @@ -45081,7 +45423,7 @@ var ts; return true; } if (!declarationList.declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } } function allowLetAndConstDeclarations(parent) { @@ -45127,7 +45469,8 @@ var ts; return true; } } - function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { + function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); if (!hasParseDiagnostics(sourceFile)) { diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; @@ -45142,7 +45485,7 @@ var ts; } function checkGrammarConstructorTypeParameters(node) { if (node.typeParameters) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + return grammarErrorAtPos(node, node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -45196,7 +45539,7 @@ var ts; node.kind === 244 /* ExportDeclaration */ || node.kind === 243 /* ExportAssignment */ || node.kind === 236 /* NamespaceExportDeclaration */ || - ts.getModifierFlags(node) & (2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { + ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -48142,7 +48485,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_8 = []; + var properties_9 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -48152,7 +48495,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_8.push(getter); + properties_9.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -48163,15 +48506,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_8.push(setter); + properties_9.push(setter); } - properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_8, multiLine) + ts.createObjectLiteral(properties_9, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -50628,11 +50971,14 @@ var ts; : numElements, location), /*reuseIdentifierExpressions*/ false, location); } - else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)) { + else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0) + || ts.every(elements, ts.isOmittedExpression)) { // For anything other than a single-element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. Additionally, if we have zero elements // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, // so in that case, we'll intentionally create that temporary. + // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]", + // then we will create temporary variable. var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); } @@ -50919,7 +51265,16 @@ var ts; if (ts.hasModifier(node, 2 /* Ambient */)) { break; } - recordEmittedDeclarationInScope(node); + // Record these declarations provided that they have a name. + if (node.name) { + recordEmittedDeclarationInScope(node); + } + else { + // These nodes should always have names unless they are default-exports; + // however, class declaration parsing allows for undefined names, so syntactically invalid + // programs may also have an undefined name. + ts.Debug.assert(node.kind === 229 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + } break; } } @@ -51748,8 +52103,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addInitializedPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { - var property = properties_9[_i]; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; var statement = ts.createStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); @@ -51764,8 +52119,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { - var property = properties_10[_i]; + for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { + var property = properties_11[_i]; var expression = transformInitializedProperty(property, receiver); expression.startsOnNewLine = true; ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); @@ -52928,33 +53283,30 @@ var ts; /** * Records that a declaration was emitted in the current scope, if it was the first * declaration for the provided symbol. - * - * NOTE: if there is ever a transformation above this one, we may not be able to rely - * on symbol names. */ function recordEmittedDeclarationInScope(node) { - var name = node.symbol && node.symbol.escapedName; - if (name) { - if (!currentScopeFirstDeclarationsOfName) { - currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); - } - if (!currentScopeFirstDeclarationsOfName.has(name)) { - currentScopeFirstDeclarationsOfName.set(name, node); - } + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); + } + var name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); } } /** - * Determines whether a declaration is the first declaration with the same name emitted - * in the current scope. + * Determines whether a declaration is the first declaration with + * the same name emitted in the current scope. */ function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name = node.symbol && node.symbol.escapedName; - if (name) { - return currentScopeFirstDeclarationsOfName.get(name) === node; - } + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; } - return false; + return true; + } + function declaredNameInScope(node) { + ts.Debug.assertNode(node.name, ts.isIdentifier); + return node.name.escapedText; } /** * Adds a leading VariableStatement for a enum or module declaration. @@ -53021,7 +53373,7 @@ var ts; if (!shouldEmitModuleDeclaration(node)) { return ts.createNotEmittedStatement(node); } - ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); + ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); enableSubstitutionForNamespaceExports(); var statements = []; // We request to be advised when the printer is about to print this node. This allows @@ -54050,6 +54402,8 @@ var ts; return visitExpressionStatement(node); case 185 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); + case 260 /* CatchClause */: + return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); } @@ -54130,6 +54484,12 @@ var ts; function visitParenthesizedExpression(node, noDestructuringValue) { return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } /** * Visits a BinaryExpression that contains a destructuring assignment. * @@ -54674,7 +55034,7 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -55378,7 +55738,7 @@ var ts; function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && ts.isStatement(node)) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 207 /* Block */))) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) || isTypeScriptClassWrapper(node); } @@ -55733,10 +56093,12 @@ var ts; var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); ts.setEmitFlags(outer, 1536 /* NoComments */); - return ts.createParen(ts.createCall(outer, + var result = ts.createParen(ts.createCall(outer, /*typeArguments*/ undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); + ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class "); + return result; } /** * Transforms a ClassExpression or ClassDeclaration into a function body. @@ -56654,13 +57016,14 @@ var ts; ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); if (node.transformFlags & 8388608 /* ContainsBindingPattern */ - && (ts.isBindingPattern(node.declarations[0].name) - || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. var firstDeclaration = ts.firstOrUndefined(declarations); - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + if (firstDeclaration) { + var lastDeclaration = ts.lastOrUndefined(declarations); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } } return declarationList; } @@ -57405,6 +57768,7 @@ var ts; function visitCatchClause(node) { var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); var updated; + ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); if (ts.isBindingPattern(node.variableDeclaration.name)) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); var newVariableDeclaration = ts.createVariableDeclaration(temp); @@ -59593,8 +59957,13 @@ var ts; } function transformAndEmitContinueStatement(node) { var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); - ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); - emitBreak(label, /*location*/ node); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid continue without a containing loop. Leave the node as is, per #17875. + emitStatement(node); + } } function visitContinueStatement(node) { if (inStatementContainingYield) { @@ -59607,8 +59976,13 @@ var ts; } function transformAndEmitBreakStatement(node) { var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); - ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); - emitBreak(label, /*location*/ node); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875. + emitStatement(node); + } } function visitBreakStatement(node) { if (inStatementContainingYield) { @@ -59979,9 +60353,6 @@ var ts; var block = endBlock(); markLabel(block.endLabel); } - function isWithBlock(block) { - return block.kind === 1 /* With */; - } /** * Begins a code block for a generated `try` statement. */ @@ -60065,9 +60436,6 @@ var ts; emitNop(); exception.state = 3 /* Done */; } - function isExceptionBlock(block) { - return block.kind === 0 /* Exception */; - } /** * Begins a code block that supports `break` or `continue` statements that are defined in * the source tree and not from generated code. @@ -60218,23 +60586,24 @@ var ts; * @param labelText An optional name of a containing labeled statement. */ function findBreakTarget(labelText) { - ts.Debug.assert(blocks !== undefined); - if (labelText) { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { - return block.breakLabel; - } - else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { - return block.breakLabel; + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } } } - } - else { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledBreak(block)) { - return block.breakLabel; + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } } } } @@ -60246,20 +60615,21 @@ var ts; * @param labelText An optional name of a containing labeled statement. */ function findContinueTarget(labelText) { - ts.Debug.assert(blocks !== undefined); - if (labelText) { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { - return block.continueLabel; + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } } } - } - else { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledContinue(block)) { - return block.continueLabel; + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } } } } @@ -60301,7 +60671,7 @@ var ts; * @param location An optional source map location for the statement. */ function createInlineBreak(label, location) { - ts.Debug.assert(label > 0, "Invalid label: " + label); + ts.Debug.assertLessThan(0, label, "Invalid label"); return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ createInstruction(3 /* Break */), createLabel(label) @@ -60642,31 +61012,33 @@ var ts; for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { var block = blocks[blockIndex]; var blockAction = blockActions[blockIndex]; - if (isExceptionBlock(block)) { - if (blockAction === 0 /* Open */) { - if (!exceptionBlockStack) { - exceptionBlockStack = []; + switch (block.kind) { + case 0 /* Exception */: + if (blockAction === 0 /* Open */) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; } - if (!statements) { - statements = []; + else if (blockAction === 1 /* Close */) { + currentExceptionBlock = exceptionBlockStack.pop(); } - exceptionBlockStack.push(currentExceptionBlock); - currentExceptionBlock = block; - } - else if (blockAction === 1 /* Close */) { - currentExceptionBlock = exceptionBlockStack.pop(); - } - } - else if (isWithBlock(block)) { - if (blockAction === 0 /* Open */) { - if (!withBlockStack) { - withBlockStack = []; + break; + case 1 /* With */: + if (blockAction === 0 /* Open */) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); } - withBlockStack.push(block); - } - else if (blockAction === 1 /* Close */) { - withBlockStack.pop(); - } + else if (blockAction === 1 /* Close */) { + withBlockStack.pop(); + } + break; } } } @@ -64580,14 +64952,14 @@ var ts; writer.writeLine(); } } - function emitTrailingCommentsOfPosition(pos) { + function emitTrailingCommentsOfPosition(pos, prefixSpace) { if (disabled) { return; } if (extendedDiagnostics) { ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); } - forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); if (extendedDiagnostics) { ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); } @@ -64676,17 +65048,7 @@ var ts; * @return true if the comment is a triple-slash comment else false */ function isTripleSlashComment(commentPos, commentEnd) { - // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text - // so that we don't end up computing comment string and doing match for all // comments - if (currentText.charCodeAt(commentPos + 1) === 47 /* slash */ && - commentPos + 2 < commentEnd && - currentText.charCodeAt(commentPos + 2) === 47 /* slash */) { - var textSubStr = currentText.substring(commentPos, commentEnd); - return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || - textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? - true : false; - } - return false; + return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); } } ts.createCommentWriter = createCommentWriter; @@ -64972,7 +65334,6 @@ var ts; errorNameNode = declaration.name; var format = 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */ | - 2048 /* UseTypeAliasValue */ | (shouldUseResolverType ? 8192 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; @@ -64987,7 +65348,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 2048 /* UseTypeAliasValue */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); errorNameNode = undefined; } } @@ -65225,7 +65586,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 2048 /* UseTypeAliasValue */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); write(";"); writeLine(); return tempVarName; @@ -65898,6 +66259,10 @@ var ts; return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); } function writeVariableStatement(node) { + // If binding pattern doesn't have name, then there is nothing to be emitted for declaration file i.e. const [,] = [1,2]. + if (ts.every(node.declarationList && node.declarationList.declarations, function (decl) { return decl.name && ts.isEmptyBindingPattern(decl.name); })) { + return; + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.isLet(node.declarationList)) { @@ -67437,7 +67802,9 @@ var ts; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = { kind: 23 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; + var dotToken = ts.createToken(23 /* DotToken */); + dotToken.pos = dotRangeStart; + dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } @@ -67566,7 +67933,9 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + emitLeadingCommentsOfPosition(node.operatorToken.pos); writeTokenNode(node.operatorToken); + emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -67760,8 +68129,19 @@ var ts; emitWithPrefix(" ", node.label); write(";"); } + function emitTokenWithComment(token, pos, contextNode) { + var node = contextNode && ts.getParseTreeNode(contextNode); + if (node && node.kind === contextNode.kind) { + pos = ts.skipTrivia(currentSourceFile.text, pos); + } + pos = writeToken(token, pos, /*contextNode*/ contextNode); + if (node && node.kind === contextNode.kind) { + emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); + } + return pos; + } function emitReturnStatement(node) { - writeToken(96 /* ReturnKeyword */, node.pos, /*contextNode*/ node); + emitTokenWithComment(96 /* ReturnKeyword */, node.pos, /*contextNode*/ node); emitExpressionWithPrefix(" ", node.expression); write(";"); } @@ -68237,10 +68617,12 @@ var ts; function emitCatchClause(node) { var openParenPos = writeToken(74 /* CatchKeyword */, node.pos); write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); - emit(node.variableDeclaration); - writeToken(20 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); - write(" "); + if (node.variableDeclaration) { + writeToken(19 /* OpenParenToken */, openParenPos); + emit(node.variableDeclaration); + writeToken(20 /* CloseParenToken */, node.variableDeclaration.end); + write(" "); + } emit(node.block); } // @@ -69520,6 +69902,14 @@ var ts; var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } + // Map from a stringified PackageId to the source file with that id. + // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). + // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around. + var packageIdToSourceFile = ts.createMap(); + // Maps from a SourceFile's `.path` to the name of the package it was imported with. + var sourceFileToPackageName = ts.createMap(); + // See `sourceFileIsRedirectedTo`. + var redirectTargetsSet = ts.createMap(); var filesByName = ts.createMap(); // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing @@ -69588,6 +69978,8 @@ var ts; isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsSet: redirectTargetsSet, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -69780,17 +70172,57 @@ var ts; var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2 /* Completely */; - for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { - var oldSourceFile = _a[_i]; + var oldSourceFiles = oldProgram.getSourceFiles(); + var SeenPackageName; + (function (SeenPackageName) { + SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; + SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; + })(SeenPackageName || (SeenPackageName = {})); + var seenPackageNames = ts.createMap(); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; } + ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + var fileChanged = void 0; + if (oldSourceFile.redirectInfo) { + // We got `newSourceFile` by path, so it is actually for the unredirected file. + // This lets us know if the unredirected file has changed. If it has we should break the redirect. + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + // Underlying file has changed. Might not redirect anymore. Must rebuild program. + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + newSourceFile = oldSourceFile; // Use the redirect. + } + else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + // If a redirected-to source file changes, the redirect may be broken. + if (newSourceFile !== oldSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + } + else { + fileChanged = newSourceFile !== oldSourceFile; + } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); - if (oldSourceFile !== newSourceFile) { + var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== undefined) { + // If there are 2 different source files for the same package name and at least one of them changes, + // they might become redirects. So we must rebuild the program. + var prevKind = seenPackageNames.get(packageName); + var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */; + if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) { + return oldProgram.structureIsReused = 0 /* Not */; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { // The `newSourceFile` object was created for the new program. if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed @@ -69831,8 +70263,8 @@ var ts; } 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; + for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { + var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); @@ -69875,8 +70307,8 @@ var ts; if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { return oldProgram.structureIsReused = 1 /* SafeModules */; } - for (var _d = 0, _e = oldProgram.getMissingFilePaths(); _d < _e.length; _d++) { - var p = _e[_d]; + for (var _c = 0, _d = oldProgram.getMissingFilePaths(); _c < _d.length; _c++) { + var p = _d[_c]; filesByName.set(p, undefined); } // update fileName -> file mapping @@ -69885,11 +70317,13 @@ var ts; } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _f = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _f < modifiedSourceFiles_2.length; _f++) { - var modifiedFile = modifiedSourceFiles_2[_f]; + for (var _e = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _e < modifiedSourceFiles_2.length; _e++) { + var modifiedFile = modifiedSourceFiles_2[_e]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsSet = oldProgram.redirectTargetsSet; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { @@ -70436,7 +70870,7 @@ var ts; } /** This has side effects through `findSourceFile`. */ function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, /*packageId*/ undefined); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -70453,8 +70887,25 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + var redirect = Object.create(redirectTarget); + redirect.fileName = fileName; + redirect.path = path; + redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + Object.defineProperties(redirect, { + id: { + get: function () { return this.redirectInfo.redirectTarget.id; }, + set: function (value) { this.redirectInfo.redirectTarget.id = value; }, + }, + symbol: { + get: function () { return this.redirectInfo.redirectTarget.symbol; }, + set: function (value) { this.redirectInfo.redirectTarget.symbol = value; }, + }, + }); + return redirect; + } // Get source file from normalized fileName - function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) { if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -70490,6 +70941,25 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + if (packageId) { + var packageIdKey = packageId.name + "@" + packageId.version; + var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + // Some other SourceFile already exists with this package name and version. + // Instead of creating a duplicate, just redirect to the existing one. + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); + redirectTargetsSet.set(fileFromPackageId.path, true); + filesByName.set(path, dupFile); + sourceFileToPackageName.set(path, packageId.name); + files.push(dupFile); + return dupFile; + } + else if (file) { + // This is the first source file to have this packageId. + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageId.name); + } + } filesByName.set(path, file); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); @@ -70630,7 +71100,7 @@ var ts; else if (shouldAddFile) { var path = toPath(resolvedFileName); var pos = ts.skipTrivia(file.text, file.imports[i].pos); - findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, file, pos, file.imports[i].end); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -70785,8 +71255,8 @@ var ts; } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted - if (options.outDir || - options.sourceRoot || + if (options.outDir || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { // Precalculate and cache the common source directory var dir = getCommonSourceDirectory(); @@ -71349,6 +71819,12 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, // Source Maps { name: "sourceRoot", @@ -72006,7 +72482,7 @@ var ts; if (option && typeof option.type !== "string") { var customOption = option; // Validate custom option type - if (!customOption.type.has(text)) { + if (!customOption.type.has(text.toLowerCase())) { errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); } } @@ -72306,13 +72782,10 @@ var ts; } } else { - // If no includes were specified, exclude common package folders and the outDir - var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - specs.push(outDir); + excludeSpecs = [outDir]; } - excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; @@ -72573,7 +73046,7 @@ var ts; return value; } else if (typeof option.type !== "string") { - return option.type.get(value); + return option.type.get(typeof value === "string" ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -72748,23 +73221,13 @@ var ts; }; } function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { - var validSpecs = []; - for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { - var spec = specs_1[_i]; - if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); } - else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); - } - else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); - } - else { - validSpecs.push(spec); - } - } - return validSpecs; + return diag === undefined; + }); function createDiagnostic(message, spec) { if (jsonSourceFile && jsonSourceFile.jsonObject) { for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { @@ -72782,6 +73245,17 @@ var ts; return ts.createCompilerDiagnostic(message, spec); } } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } /** * Gets directories in a set of include patterns that should be watched for changes. */ @@ -72945,7 +73419,7 @@ var ts; (function (ts) { var ScriptSnapshot; (function (ScriptSnapshot) { - var StringScriptSnapshot = (function () { + var StringScriptSnapshot = /** @class */ (function () { function StringScriptSnapshot(text) { this.text = text; } @@ -72969,7 +73443,7 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); - var TextChange = (function () { + var TextChange = /** @class */ (function () { function TextChange() { } return TextChange; @@ -73831,8 +74305,14 @@ var ts; } } ts.findNextToken = findNextToken; + /** + * Finds the rightmost token satisfying `token.end <= position`, + * excluding `JsxText` tokens containing only whitespace. + */ function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { - return find(startNode || sourceFile); + var result = find(startNode || sourceFile); + ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); + return result; function findRightmostToken(n) { if (ts.isToken(n)) { return n; @@ -73848,18 +74328,16 @@ var ts; var children = n.getChildren(); for (var i = 0; i < children.length; i++) { var child = children[i]; - // condition 'position < child.end' checks if child node end after the position - // in the example below this condition will be false for 'aaaa' and 'bbbb' and true for 'ccc' - // aaaa___bbbb___$__ccc - // after we found child node with end after the position we check if start of the node is after the position. - // if yes - then position is in the trivia and we need to look into the previous child to find the token in question. - // if no - position is in the node itself so we should recurse in it. - // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). - // if this is the case - then we should assume that token in question is located in previous child. - if (position < child.end && (nodeHasTokens(child) || child.kind === 10 /* JsxText */)) { + // Note that the span of a node's tokens is [node.getStart(...), node.end). + // Given that `position < child.end` and child has constituent tokens, we distinguish these cases: + // 1) `position` precedes `child`'s tokens or `child` has no tokens (ie: in a comment or whitespace preceding `child`): + // we need to find the last token in a previous child. + // 2) `position` is within the same span: we recurse on `child`. + if (position < child.end) { var start = child.getStart(sourceFile, includeJsDoc); - var lookInPreviousChild = (start >= position) || - (child.kind === 10 /* JsxText */ && start === child.end); // whitespace only JsxText + var lookInPreviousChild = (start >= position) || // cursor in the leading trivia + !nodeHasTokens(child) || + isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); @@ -73881,10 +74359,16 @@ var ts; return candidate && findRightmostToken(candidate); } } - /// finds last node that is considered as candidate for search (isCandidate(node) === true) starting from 'exclusiveStartPosition' + /** + * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. + */ function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { for (var i = exclusiveStartPosition - 1; i >= 0; i--) { - if (nodeHasTokens(children[i])) { + var child = children[i]; + if (isWhiteSpaceOnlyJsxText(child)) { + ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + } + else if (nodeHasTokens(children[i])) { return children[i]; } } @@ -73942,6 +74426,10 @@ var ts; return false; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isWhiteSpaceOnlyJsxText(node) { + return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; + } + ts.isWhiteSpaceOnlyJsxText = isWhiteSpaceOnlyJsxText; function isInTemplateString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); @@ -73954,39 +74442,9 @@ var ts; * @param predicate Additional predicate to test on the comment range. */ function isInComment(sourceFile, position, tokenAtPosition, predicate) { - if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } - return position <= tokenAtPosition.getStart(sourceFile) && - (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || - isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); - function isInCommentRange(commentRanges) { - return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); - } + return !!ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ false, /*precedingToken*/ undefined, tokenAtPosition, predicate); } 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): - // - // // asdf ^\n - // - // But for multi-line comments, we don't want to be inside the comment in the following case: - // - // /* asdf */^ - // - // Internally, we represent the end of the comment at the newline and closing '/', respectively. - 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; - } - } function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // First, we have to see if this position actually landed in a comment. @@ -74000,7 +74458,7 @@ var ts; ts.hasDocComment = hasDocComment; function nodeHasTokens(n) { // If we have a token or node that has a non-zero width, it must have tokens. - // Note, that getWidth() does not take trivia into account. + // Note: getWidth() does not take trivia into account. return n.getWidth() !== 0; } function getNodeModifiers(node) { @@ -74357,6 +74815,7 @@ var ts; } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + flags |= 65536 /* UseAliasDefinedOutsideCurrentScope */; return mapToDisplayParts(function (writer) { typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); }); @@ -74666,11 +75125,11 @@ var ts; templateStack.pop(); } else { - ts.Debug.assert(token === 15 /* TemplateMiddle */, "Should have been a template middle. Was " + token); + ts.Debug.assertEqual(token, 15 /* TemplateMiddle */, "Should have been a template middle."); } } else { - ts.Debug.assert(lastTemplateStackToken === 17 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); + ts.Debug.assertEqual(lastTemplateStackToken, 17 /* OpenBraceToken */, "Should have been an open brace"); templateStack.pop(); } } @@ -76652,7 +77111,7 @@ var ts; if (!typeForObject) return false; // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. - typeMembers = typeChecker.getPropertiesOfType(typeForObject); + typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24 /* NonPublicAccessibilityModifier */); }); existingMembers = objectLikeContainer.elements; } } @@ -76916,11 +77375,11 @@ var ts; return containingNodeKind === 226 /* VariableDeclaration */ || containingNodeKind === 227 /* VariableDeclarationList */ || containingNodeKind === 208 /* VariableStatement */ || - containingNodeKind === 232 /* EnumDeclaration */ || + containingNodeKind === 232 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 230 /* InterfaceDeclaration */ || - containingNodeKind === 175 /* ArrayBindingPattern */ || - containingNodeKind === 231 /* TypeAliasDeclaration */ || + containingNodeKind === 230 /* InterfaceDeclaration */ || // interface A undefined); => should get use to the declaration in file "./foo" + // + // function bar(onfulfilled: (value: T) => void) { //....} + // interface Test { + // pr/*destination*/op1: number + // } + // bar(({pr/*goto*/op1})=>{}); + if (ts.isPropertyName(node) && ts.isBindingElement(node.parent) && ts.isObjectBindingPattern(node.parent.parent) && + (node === (node.parent.propertyName || node.parent.name))) { + var type = typeChecker.getTypeAtLocation(node.parent.parent); + if (type) { + var propSymbols = ts.getPropertySymbolsFromType(type, node); + if (propSymbols) { + return ts.flatMap(propSymbols, function (propSymbol) { return getDefinitionFromSymbol(typeChecker, propSymbol, node); }); + } + } + } // 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 @@ -80614,12 +81104,20 @@ var ts; "crypto", "stream", "util", "assert", "tty", "domain", "constants", "process", "v8", "timers", "console" ]; - var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); + var nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); function loadSafeList(host, safeListPath) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); return ts.createMapFromTemplate(result.config); } JsTyping.loadSafeList = loadSafeList; + function loadTypesMap(host, typesMapPath) { + var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); + if (result.config) { + return ts.createMapFromTemplate(result.config.simpleMap); + } + return undefined; + } + JsTyping.loadTypesMap = loadTypesMap; /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -80812,8 +81310,8 @@ var ts; if (!matches) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. if (patternMatcher.patternContainsDots) { @@ -81549,13 +82047,18 @@ var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { + var collapseText = "..."; + var maxDepth = 20; function collectElements(sourceFile, cancellationToken) { var elements = []; - var collapseText = "..."; - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { + var depth = 0; + walk(sourceFile); + return elements; + /** If useFullStart is true, then the collapsing span includes leading whitespace, including linebreaks. */ + function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { if (hintSpanNode && startElement && endElement) { var span_13 = { - textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), + textSpan: ts.createTextSpanFromBounds(useFullStart ? startElement.getFullStart() : startElement.getStart(), endElement.getEnd()), hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), bannerText: collapseText, autoCollapse: autoCollapse, @@ -81619,8 +82122,6 @@ var ts; function autoCollapse(node) { return ts.isFunctionBlock(node) && node.parent.kind !== 187 /* ArrowFunction */; } - var depth = 0; - var maxDepth = 20; function walk(n) { cancellationToken.throwIfCancellationRequested(); if (depth > maxDepth) { @@ -81633,8 +82134,8 @@ var ts; case 207 /* Block */: if (!ts.isFunctionBlock(n)) { var parent = n.parent; - var openBrace = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); + var openBrace_1 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); + var closeBrace_1 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. @@ -81646,20 +82147,20 @@ var ts; parent.kind === 213 /* WhileStatement */ || parent.kind === 220 /* WithStatement */ || parent.kind === 260 /* CatchClause */) { - addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); break; } if (parent.kind === 224 /* TryStatement */) { // Could be the try-block, or the finally-block. var tryStatement = parent; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); break; } else if (tryStatement.finallyBlock === n) { var finallyKeyword = ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile); if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(finallyKeyword, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); break; } } @@ -81678,33 +82179,38 @@ var ts; } // falls through case 234 /* ModuleBlock */: { - var openBrace = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + var openBrace_2 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); + var closeBrace_2 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n.parent, openBrace_2, closeBrace_2, autoCollapse(n), /*useFullStart*/ true); break; } case 229 /* ClassDeclaration */: case 230 /* InterfaceDeclaration */: case 232 /* EnumDeclaration */: - case 178 /* ObjectLiteralExpression */: case 235 /* CaseBlock */: { - var openBrace = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); + var openBrace_3 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); + var closeBrace_3 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n, openBrace_3, closeBrace_3, autoCollapse(n), /*useFullStart*/ true); break; } + // If the block has no leading keywords and is inside an array literal, + // we only want to collapse the span of the block. + // Otherwise, the collapsed section will include the end of the previous line. + case 178 /* ObjectLiteralExpression */: + var openBrace = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n), /*useFullStart*/ !ts.isArrayLiteralExpression(n.parent)); + break; case 177 /* ArrayLiteralExpression */: var openBracket = ts.findChildOfKind(n, 21 /* OpenBracketToken */, sourceFile); var closeBracket = ts.findChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); + addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n), /*useFullStart*/ !ts.isArrayLiteralExpression(n.parent)); break; } depth++; ts.forEachChild(n, walk); depth--; } - walk(sourceFile); - return elements; } OutliningElementsCollector.collectElements = collectElements; })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); @@ -82760,8 +83266,8 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - for (var _b = 0, declarations_13 = declarations; _b < declarations_13.length; _b++) { - var declaration = declarations_13[_b]; + for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { + var declaration = declarations_12[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -82820,7 +83326,9 @@ var ts; } var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; var argumentCount = getArgumentCount(list); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } @@ -82942,7 +83450,9 @@ var ts; var argumentCount = tagExpression.template.kind === 13 /* NoSubstitutionTemplateLiteral */ ? 1 : tagExpression.template.templateSpans.length + 1; - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } return { kind: 2 /* TaggedTemplateArguments */, invocation: tagExpression, @@ -83060,7 +83570,9 @@ var ts; tags: candidateSignature.getJsDocTags() }; }); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } var selectedItemIndex = candidates.indexOf(resolvedSignature); ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; @@ -83209,114 +83721,112 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (type) { - if (location.parent && location.parent.kind === 179 /* PropertyAccessExpression */) { - var right = location.parent.name; - // Either the location is on the right of a property access, or on the left and the right is missing - if (right === location || (right && right.getFullWidth() === 0)) { - location = location.parent; + if (location.parent && location.parent.kind === 179 /* PropertyAccessExpression */) { + var right = location.parent.name; + // Either the location is on the right of a property access, or on the left and the right is missing + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + // try get the call/construct signature from the type if it matches + var callExpressionLike = void 0; + if (ts.isCallOrNewExpression(location)) { + callExpressionLike = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpressionLike = location.parent; + } + else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { + callExpressionLike = location.parent; + } + if (callExpressionLike) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); + if (!signature && candidateSignatures.length) { + // Use the first candidate: + signature = candidateSignatures[0]; + } + var useConstructSignatures = callExpressionLike.kind === 182 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + // Get the first signature if there is one -- allSignatures may contain + // either the original signature or its target, so check for either + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { + // Constructor + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } - } - // try get the call/construct signature from the type if it matches - var callExpressionLike = void 0; - if (ts.isCallOrNewExpression(location)) { - callExpressionLike = location; - } - else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { - callExpressionLike = location.parent; - } - else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { - callExpressionLike = location.parent; - } - if (callExpressionLike) { - var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); - if (!signature && candidateSignatures.length) { - // Use the first candidate: - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpressionLike.kind === 182 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); - var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { - // Get the first signature if there is one -- allSignatures may contain - // either the original signature or its target, so check for either - signature = allSignatures.length ? allSignatures[0] : undefined; - } - if (signature) { - if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { - // Constructor - symbolKind = "constructor" /* constructorImplementationElement */; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + else if (symbolFlags & 2097152 /* Alias */) { + symbolKind = "alias" /* alias */; + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + displayParts.push(ts.spacePart()); } - else if (symbolFlags & 2097152 /* Alias */) { - symbolKind = "alias" /* alias */; - pushTypePart(symbolKind); + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case "JSX attribute" /* jsxAttribute */: + case "property" /* memberVariableElement */: + case "var" /* variableElement */: + case "const" /* constElement */: + case "let" /* letElement */: + case "parameter" /* parameterElement */: + case "local var" /* localVariableElement */: + // If it is call or construct signature of lambda's write type name + displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - addFullSymbolName(symbol); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - switch (symbolKind) { - case "JSX attribute" /* jsxAttribute */: - case "property" /* memberVariableElement */: - case "var" /* variableElement */: - case "const" /* constElement */: - case "let" /* letElement */: - case "parameter" /* parameterElement */: - case "local var" /* localVariableElement */: - // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(56 /* ColonToken */)); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); - displayParts.push(ts.spacePart()); - } - if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); - } - addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); - break; - default: - // Just signature - addSignatureDisplayParts(signature, allSignatures); - } - hasAddedSymbolInfo = true; + if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + } + addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); + break; + default: + // Just signature + addSignatureDisplayParts(signature, allSignatures); } + hasAddedSymbolInfo = true; } - else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 152 /* Constructor */)) { - // get the signature from the declaration and write it - var functionDeclaration_1 = location.parent; - // Use function declaration to write the signatures only if the symbol corresponding to this declaration - var locationIsSymbolDeclaration = ts.findDeclaration(symbol, function (declaration) { - return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); - }); - if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 152 /* Constructor */ ? 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 /* Constructor */) { - // show (constructor) Type(...) signature - symbolKind = "constructor" /* constructorImplementationElement */; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 /* CallSignature */ && - !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration + (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 152 /* Constructor */)) { + // get the signature from the declaration and write it + var functionDeclaration_1 = location.parent; + // Use function declaration to write the signatures only if the symbol corresponding to this declaration + var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 152 /* Constructor */ ? 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 /* Constructor */) { + // show (constructor) Type(...) signature + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 /* CallSignature */ && + !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; } } } @@ -83502,7 +84012,9 @@ var ts; symbolFlags & 98304 /* Accessor */ || symbolKind === "method" /* memberFunctionElement */) { var allSignatures = type.getNonNullableType().getCallSignatures(); - addSignatureDisplayParts(allSignatures[0], allSignatures); + if (allSignatures.length) { + addSignatureDisplayParts(allSignatures[0], allSignatures); + } } } } @@ -83676,11 +84188,11 @@ var ts; getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, writeFile: function (name, text) { if (ts.fileExtensionIs(name, ".map")) { - ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); + ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name); sourceMapText = text; } else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); + ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name); outputText = text; } }, @@ -84005,7 +84517,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var FormattingContext = (function () { + var FormattingContext = /** @class */ (function () { function FormattingContext(sourceFile, formattingRequestKind, options) { this.sourceFile = sourceFile; this.formattingRequestKind = formattingRequestKind; @@ -84104,7 +84616,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var Rule = (function () { + var Rule = /** @class */ (function () { function Rule(Descriptor, Operation, Flag) { if (Flag === void 0) { Flag = 0 /* None */; } this.Descriptor = Descriptor; @@ -84142,7 +84654,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var RuleDescriptor = (function () { + var RuleDescriptor = /** @class */ (function () { function RuleDescriptor(LeftTokenRange, RightTokenRange) { this.LeftTokenRange = LeftTokenRange; this.RightTokenRange = RightTokenRange; @@ -84187,7 +84699,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var RuleOperation = (function () { + var RuleOperation = /** @class */ (function () { function RuleOperation(Context, Action) { this.Context = Context; this.Action = Action; @@ -84213,7 +84725,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var RuleOperationContext = (function () { + var RuleOperationContext = /** @class */ (function () { function RuleOperationContext() { var funcs = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -84248,7 +84760,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var Rules = (function () { + var Rules = /** @class */ (function () { function Rules() { /// /// Common Rules @@ -84407,6 +84919,7 @@ var ts; // Insert space after opening and before closing nonempty parenthesis this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenOpenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenParenToken */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenParenToken */, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); @@ -84486,7 +84999,7 @@ var ts; this.SpaceAfterComma, this.NoSpaceAfterComma, this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, - this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, + this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.SpaceBetweenOpenParens, 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, @@ -84825,7 +85338,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var RulesMap = (function () { + var RulesMap = /** @class */ (function () { function RulesMap() { this.map = []; this.mapRowLength = 0; @@ -84895,7 +85408,7 @@ var ts; RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; })(RulesPosition = formatting.RulesPosition || (formatting.RulesPosition = {})); - var RulesBucketConstructionState = (function () { + var RulesBucketConstructionState = /** @class */ (function () { function RulesBucketConstructionState() { //// The Rules list contains all the inserted rules into a rulebucket in the following order: //// 1- Ignore rules with specific token combination @@ -84936,7 +85449,7 @@ var ts; return RulesBucketConstructionState; }()); formatting.RulesBucketConstructionState = RulesBucketConstructionState; - var RulesBucket = (function () { + var RulesBucket = /** @class */ (function () { function RulesBucket() { this.rules = []; } @@ -84985,7 +85498,7 @@ var ts; for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { allTokens.push(token); } - var TokenValuesAccess = (function () { + var TokenValuesAccess = /** @class */ (function () { function TokenValuesAccess(tokens) { if (tokens === void 0) { tokens = []; } this.tokens = tokens; @@ -84999,7 +85512,7 @@ var ts; TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - var TokenSingleValueAccess = (function () { + var TokenSingleValueAccess = /** @class */ (function () { function TokenSingleValueAccess(token) { this.token = token; } @@ -85012,7 +85525,7 @@ var ts; TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - var TokenAllAccess = (function () { + var TokenAllAccess = /** @class */ (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { @@ -85027,7 +85540,7 @@ var ts; TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - var TokenAllExceptAccess = (function () { + var TokenAllExceptAccess = /** @class */ (function () { function TokenAllExceptAccess(except) { this.except = except; } @@ -85119,7 +85632,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var RulesProvider = (function () { + var RulesProvider = /** @class */ (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); @@ -85427,7 +85940,6 @@ 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, options); - var previousRangeHasError; var previousRange; var previousParent; var previousRangeStartLine; @@ -85818,7 +86330,7 @@ var ts; function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAdded; - if (!rangeHasError && !previousRangeHasError) { + if (!rangeHasError) { if (!previousRange) { // trim whitespaces starting from the beginning of the span up to the current line var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); @@ -85832,7 +86344,6 @@ var ts; previousRange = range; previousParent = parent; previousRangeStartLine = rangeStart.line; - previousRangeHasError = rangeHasError; return lineAdded; } function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { @@ -86038,6 +86549,51 @@ var ts; } } } + /** + * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. + */ + function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, // tslint:disable-line:no-null-keyword + tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } + var tokenStart = tokenAtPosition.getStart(sourceFile); + if (tokenStart <= position && position < tokenAtPosition.getEnd()) { + return undefined; + } + if (precedingToken === undefined) { + precedingToken = ts.findPrecedingToken(position, sourceFile); + } + // Between two consecutive tokens, all comments are either trailing on the former + // or leading on the latter (and none are in both lists). + var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end); + var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); + var commentRanges = trailingRangesOfPreviousToken && leadingCommentRangesOfNextToken ? + trailingRangesOfPreviousToken.concat(leadingCommentRangesOfNextToken) : + trailingRangesOfPreviousToken || leadingCommentRangesOfNextToken; + if (commentRanges) { + for (var _i = 0, commentRanges_1 = commentRanges; _i < commentRanges_1.length; _i++) { + var range = commentRanges_1[_i]; + // The end marker of a single-line comment does not include the newline character. + // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position): + // + // // asdf ^\n + // + // But for closed multi-line comments, we don't want to be inside the comment in the following case: + // + // /* asdf */^ + // + // However, unterminated multi-line comments *do* contain their end. + // + // Internally, we represent the end of the comment at the newline and closing '/', respectively. + // + if ((range.pos < position && position < range.end || + position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()))) { + return (range.kind === 3 /* MultiLineCommentTrivia */ || !onlyMultiLine) && (!predicate || predicate(range)) ? range : undefined; + } + } + } + return undefined; + } + formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { case 152 /* Constructor */: @@ -86165,12 +86721,28 @@ var ts; return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ true, precedingToken || null); // tslint:disable-line:no-null-keyword + if (enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; + } if (!precedingToken) { return getBaseIndentation(options); } // no indentation in string \regex\template literals var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); - if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) { + if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) { return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; @@ -86473,13 +87045,13 @@ var ts; var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options); } - /* - Character is the actual index of the character since the beginning of the line. - Column - position of the character after expanding tabs to spaces - "0\t2$" - value of 'character' for '$' is 3 - value of 'column' for '$' is 6 (assuming that tab size is 4) - */ + /** + * Character is the actual index of the character since the beginning of the line. + * Column - position of the character after expanding tabs to spaces. + * "0\t2$" + * value of 'character' for '$' is 3 + * value of 'column' for '$' is 6 (assuming that tab size is 4) + */ function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { var character = 0; var column = 0; @@ -86633,6 +87205,12 @@ var ts; } return false; } + var ChangeKind; + (function (ChangeKind) { + ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; + ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; + ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + })(ChangeKind || (ChangeKind = {})); function getSeparatorCharacter(separator) { return ts.tokenToString(separator.kind); } @@ -86666,13 +87244,11 @@ var ts; } textChanges.getAdjustedStartPosition = getAdjustedStartPosition; function getAdjustedEndPosition(sourceFile, node, options) { - if (options.useNonAdjustedEndPosition) { + if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { return node.getEnd(); } var end = node.getEnd(); var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); - // check if last character before newPos is linebreak - // if yes - considered all skipped trivia to be trailing trivia of the node return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) ? newEnd : end; @@ -86691,7 +87267,10 @@ var ts; } return s; } - var ChangeTracker = (function () { + function getNewlineKind(context) { + return context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + } + var ChangeTracker = /** @class */ (function () { function ChangeTracker(newLine, rulesProvider, validator) { this.newLine = newLine; this.rulesProvider = rulesProvider; @@ -86700,24 +87279,24 @@ var ts; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromCodeFixContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.rulesProvider); + return new ChangeTracker(getNewlineKind(context), context.rulesProvider); + }; + ChangeTracker.prototype.deleteRange = function (sourceFile, range) { + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); + return this; }; ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, node, options); - this.changes.push({ sourceFile: sourceFile, options: options, range: { pos: startPosition, end: endPosition } }); - return this; - }; - ChangeTracker.prototype.deleteRange = function (sourceFile, range) { - this.changes.push({ sourceFile: sourceFile, range: range }); + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); return this; }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, range: { pos: startPosition, end: endPosition } }); + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); return this; }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { @@ -86756,33 +87335,68 @@ var ts; }; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ sourceFile: sourceFile, range: range, options: options, node: newNode }); + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); return this; }; ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: endPosition } }); - return this; + return this.replaceWithSingle(sourceFile, startPosition, endPosition, newNode, options); }; ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: endPosition } }); + return this.replaceWithSingle(sourceFile, startPosition, endPosition, newNode, options); + }; + ChangeTracker.prototype.replaceWithSingle = function (sourceFile, startPosition, endPosition, newNode, options) { + this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, + sourceFile: sourceFile, + options: options, + node: newNode, + range: { pos: startPosition, end: endPosition } + }); return this; }; + ChangeTracker.prototype.replaceWithMultiple = function (sourceFile, startPosition, endPosition, newNodes, options) { + this.changes.push({ + kind: ChangeKind.ReplaceWithMultipleNodes, + sourceFile: sourceFile, + options: options, + nodes: newNodes, + range: { pos: startPosition, end: endPosition } + }); + return this; + }; + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; + ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, oldNodes[0], options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, ts.lastOrUndefined(oldNodes), options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; + ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { + return this.replaceWithMultiple(sourceFile, range.pos, range.end, newNodes, options); + }; + ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); return this; }; ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, before, options, Position.Start); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: startPosition } }); - return this; + return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, options); }; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { if (options === void 0) { options = {}; } @@ -86794,6 +87408,7 @@ var ts; // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: {}, range: { pos: after.end, end: after.end }, @@ -86802,8 +87417,7 @@ var ts; } } var endPosition = getAdjustedEndPosition(sourceFile, after, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: endPosition, end: endPosition } }); - return this; + return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, options); }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, @@ -86869,10 +87483,10 @@ var ts; startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); } this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: startPos, end: containingList[index + 1].getStart(sourceFile) }, node: newNode, - useIndentationFromFile: true, options: { prefix: prefix, // write separator and leading trivia of the next element as suffix @@ -86911,6 +87525,7 @@ var ts; if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: end, end: end }, node: ts.createToken(separator), @@ -86924,6 +87539,7 @@ var ts; insertPos--; } this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: insertPos, end: insertPos }, node: newNode, @@ -86932,6 +87548,7 @@ var ts; } else { this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: end, end: end }, node: newNode, @@ -86973,34 +87590,46 @@ var ts; return ts.createTextSpanFromBounds(change.range.pos, change.range.end); }; ChangeTracker.prototype.computeNewText = function (change, sourceFile) { - if (!change.node) { + var _this = this; + if (change.kind === ChangeKind.Remove) { // deletion case return ""; } var options = change.options || {}; - var nonFormattedText = getNonformattedText(change.node, sourceFile, this.newLine); - if (this.validator) { - this.validator(nonFormattedText); - } - var formatOptions = this.rulesProvider.getFormatOptions(); + var text; var pos = change.range.pos; var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - var initialIndentation = change.options.indentation !== undefined - ? change.options.indentation - : change.useIndentationFromFile - ? ts.formatting.SmartIndenter.getIndentation(change.range.pos, sourceFile, formatOptions, posStartsLine || (change.options.prefix === this.newLineCharacter)) - : 0; - var delta = change.options.delta !== undefined - ? change.options.delta - : ts.formatting.SmartIndenter.shouldIndentChildNode(change.node) - ? formatOptions.indentSize - : 0; - var text = applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, this.rulesProvider); + if (change.kind === ChangeKind.ReplaceWithMultipleNodes) { + var parts = change.nodes.map(function (n) { return _this.getFormattedTextOfNode(n, sourceFile, pos, options); }); + text = parts.join(change.options.nodeSeparator); + } + else { + ts.Debug.assert(change.kind === ChangeKind.ReplaceWithSingleNode, "change.kind === ReplaceWithSingleNode"); + text = this.getFormattedTextOfNode(change.node, sourceFile, pos, options); + } // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line - // however keep indentation if it is was forced - text = posStartsLine || change.options.indentation !== undefined ? text : text.replace(/^\s+/, ""); + text = (posStartsLine || options.indentation !== undefined) ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + text + (options.suffix || ""); }; + ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) { + var nonformattedText = getNonformattedText(node, sourceFile, this.newLine); + if (this.validator) { + this.validator(nonformattedText); + } + var formatOptions = this.rulesProvider.getFormatOptions(); + var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; + var initialIndentation = options.indentation !== undefined + ? options.indentation + : (options.useIndentationFromFile !== false) + ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter)) + : 0; + var delta = options.delta !== undefined + ? options.delta + : ts.formatting.SmartIndenter.shouldIndentChildNode(node) + ? (formatOptions.indentSize || 0) + : 0; + return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.rulesProvider); + }; ChangeTracker.normalize = function (changes) { // order changes by start position var normalized = ts.stableSort(changes, function (a, b) { return a.range.pos - b.range.pos; }); @@ -87065,7 +87694,7 @@ var ts; nodeArray.end = getEnd(nodes); return nodeArray; } - var Writer = (function () { + var Writer = /** @class */ (function () { function Writer(newLine) { var _this = this; this.lastNonTriviaPosition = 0; @@ -87948,7 +88577,7 @@ var ts; ModuleSpecifierComparison[ModuleSpecifierComparison["Equal"] = 1] = "Equal"; ModuleSpecifierComparison[ModuleSpecifierComparison["Worse"] = 2] = "Worse"; })(ModuleSpecifierComparison || (ModuleSpecifierComparison = {})); - var ImportCodeActionMap = (function () { + var ImportCodeActionMap = /** @class */ (function () { function ImportCodeActionMap() { this.symbolIdToActionMap = []; } @@ -88061,7 +88690,7 @@ var ts; } else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - symbol = checker.getAliasedSymbol(checker.resolveNameAtLocation(token, checker.getJsxNamespace(), 107455 /* Value */)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455 /* Value */)); symbolName = symbol.name; } else { @@ -88086,7 +88715,7 @@ var ts; if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { // check if this symbol is already used var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isDefault*/ true)); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isNamespaceImport*/ true)); } } // "default" is a keyword and not a legal identifier for the import, so we don't expect it here @@ -88162,8 +88791,8 @@ var ts; var namespaceImportDeclaration; var namedImportDeclaration; var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (declaration.kind === 238 /* ImportDeclaration */) { var namedBindings = declaration.importClause && declaration.importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { @@ -88273,9 +88902,11 @@ var ts; : isNamespaceImport ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); + moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifierLiteral); if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeAt(sourceFile, getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); } else { changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); @@ -88284,6 +88915,46 @@ var ts; // 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, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getSourceFileImportLocation(node) { + // For a source file, it is possible there are detached comments we should not skip + var text = node.text; + var ranges = ts.getLeadingCommentRanges(text, 0); + if (!ranges) + return 0; + var position = 0; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end + 1; + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(node.text, range.pos, range.end)) { + position = range.end + 1; + continue; + } + break; + } + return position; + } + function getSingleQuoteStyleFromExistingImports() { + var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { + if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { + if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { + return node.moduleSpecifier; + } + } + else if (ts.isImportEqualsDeclaration(node)) { + if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { + return node.moduleReference.expression; + } + } + }); + if (firstModuleSpecifier) { + return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39 /* singleQuote */; + } + } function getModuleSpecifierForNewImport() { var fileName = sourceFile.fileName; var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; @@ -88415,8 +89086,8 @@ var ts; } function getNodeModulePathParts(fullPath) { // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[otherpackage/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ var topLevelNodeModulesIndex = 0; var topLevelPackageNameIndex = 0; var packageRootIndex = 0; @@ -88425,7 +89096,8 @@ var ts; (function (States) { States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; States[States["NodeModules"] = 1] = "NodeModules"; - States[States["PackageContent"] = 2] = "PackageContent"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; })(States || (States = {})); var partStart = 0; var partEnd = 0; @@ -88442,15 +89114,21 @@ var ts; } break; case 1 /* NodeModules */: - packageRootIndex = partEnd; - state = 2 /* PackageContent */; + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } break; - case 2 /* PackageContent */: + case 3 /* PackageContent */: if (fullPath.indexOf("/node_modules/", partStart) === partStart) { state = 1 /* NodeModules */; } else { - state = 2 /* PackageContent */; + state = 3 /* PackageContent */; } break; } @@ -88807,231 +89485,1208 @@ var ts; (function (ts) { var refactor; (function (refactor) { - var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); - function getAvailableActions(context) { - if (!ts.isInJavaScriptFile(context.file)) { - return undefined; + var convertFunctionToES6Class; + (function (convertFunctionToES6Class_1) { + var actionName = "convert"; + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions + }; + refactor.registerRefactor(convertFunctionToES6Class); + function getAvailableActions(context) { + if (!ts.isInJavaScriptFile(context.file)) { + return undefined; + } + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + if (symbol && (symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { + return [ + { + name: convertFunctionToES6Class.name, + description: convertFunctionToES6Class.description, + actions: [ + { + description: convertFunctionToES6Class.description, + name: actionName + } + ] + } + ]; + } } - var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - var symbol = checker.getSymbolAtLocation(node); - if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = symbol.valueDeclaration.initializer.symbol; - } - if (symbol && (symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { - return [ - { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, - actions: [ - { - description: convertFunctionToES6Class.description, - name: actionName - } - ] + function getEditsForAction(context, action) { + // Somehow wrong action got invoked? + if (actionName !== action) { + return undefined; + } + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + return undefined; + } + 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 undefined; + } + // 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 { + edits: 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; } - ]; - } - } - function getEditsForAction(context, action) { - // Somehow wrong action got invoked? - if (actionName !== action) { - return undefined; - } - var start = context.startPosition; - var sourceFile = context.file; - var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var ctorSymbol = checker.getSymbolAtLocation(token); - var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; - var deletedNodes = []; - var deletes = []; - if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { - return undefined; - } - 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); + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); } else { - deleteNode(ctorDeclaration, /*inList*/ true); + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); } - newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); - break; - } - if (!newClassDeclaration) { - return undefined; - } - // 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 { - edits: 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); }); + 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; + var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + copyComments(assignmentBinaryExpression, method); + return method; + } + 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)]); + } + var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + copyComments(assignmentBinaryExpression, method); + return method; + } + default: { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop); + return prop; + } + } + } + } + function copyComments(sourceNode, targetNode) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // Remove leading /* + pos += 2; + // Remove trailing */ + end -= 2; + } + else { + // Remove leading // + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + }); + } + 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)); + } + var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + } + })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/// +/// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var extractMethod; + (function (extractMethod_1) { + var extractMethod = { + name: "Extract Method", + description: ts.Diagnostics.Extract_function.message, + getAvailableActions: getAvailableActions, + getEditsForAction: getEditsForAction, + }; + refactor.registerRefactor(extractMethod); + /** Compute the associated code actions */ + function getAvailableActions(context) { + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: context.endPosition - context.startPosition }); + var targetRange = rangeToExtract.targetRange; + if (targetRange === undefined) { + return undefined; + } + var extractions = getPossibleExtractions(targetRange, context); + if (extractions === undefined) { + // No extractions possible + return undefined; + } + var actions = []; + var usedNames = ts.createMap(); + var i = 0; + for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { + var extr = extractions_1[_i]; + // Skip these since we don't have a way to report errors yet + if (extr.errors && extr.errors.length) { + continue; + } + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_function_into_0.message, [extr.scopeDescription]); + if (!usedNames.has(description)) { + usedNames.set(description, true); + actions.push({ + description: description, + name: "scope_" + i + }); + } + // *do* increment i anyway because we'll look for the i-th scope + // later when actually doing the refactoring if the user requests it + i++; + } + if (actions.length === 0) { + return undefined; + } + return [{ + name: extractMethod.name, + description: extractMethod.description, + inlineable: true, + actions: actions + }]; + } + function getEditsForAction(context, actionName) { + var length = context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: length }); + var targetRange = rangeToExtract.targetRange; + var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); + ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); + var index = +parsedIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); + var extractions = getPossibleExtractions(targetRange, context, index); + // Scope is no longer valid from when the user issued the refactor (??) + ts.Debug.assert(extractions !== undefined, "The extraction went missing? How?"); + return ({ edits: extractions[0].changes }); + } + // Move these into diagnostic messages if they become user-facing + var Messages; + (function (Messages) { + function createMessage(message) { + return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; + } + Messages.CannotExtractFunction = createMessage("Cannot extract function."); + Messages.StatementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.CannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.TypeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.InsufficientSelection = createMessage("Select more than a single identifier."); + Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); + Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + })(Messages || (Messages = {})); + var RangeFacts; + (function (RangeFacts) { + RangeFacts[RangeFacts["None"] = 0] = "None"; + RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn"; + RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis"; + /** + * The range is in a function which needs the 'static' modifier in a class + */ + RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; + })(RangeFacts = extractMethod_1.RangeFacts || (extractMethod_1.RangeFacts = {})); + /** + * getRangeToExtract takes a span inside a text file and returns either an expression or an array + * of statements representing the minimum set of nodes needed to extract the entire span. This + * process may fail, in which case a set of errors is returned instead (these are currently + * not shown to the user, but can be used by us diagnostically) + */ + function getRangeToExtract(sourceFile, span) { + var length = span.length || 0; + // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. + // This may fail (e.g. you select two statements in the root of a source file) + var start = getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false), sourceFile, span); + // Do the same for the ending position + var end = getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); + var declarations = []; + // We'll modify these flags as we walk the tree to collect data + // about what things need to be done as part of the extraction. + var rangeFacts = RangeFacts.None; + if (!start || !end) { + // cannot find either start or end node + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractFunction)] }; + } + if (start.parent !== end.parent) { + // handle cases like 1 + [2 + 3] + 4 + // user selection is marked with []. + // in this case 2 + 3 does not belong to the same tree node + // instead the shape of the tree looks like this: + // + + // / \ + // + 4 + // / \ + // + 3 + // / \ + // 1 2 + // in this case there is no such one node that covers ends of selection and is located inside the selection + // to handle this we check if both start and end of the selection belong to some binary operation + // and start node is parented by the parent of the end node + // if this is the case - expand the selection to the entire parent of end node (in this case it will be [1 + 2 + 3] + 4) + var startParent = ts.skipParentheses(start.parent); + var endParent = ts.skipParentheses(end.parent); + if (ts.isBinaryExpression(startParent) && ts.isBinaryExpression(endParent) && ts.isNodeDescendantOf(startParent, endParent)) { + start = end = endParent; + } + else { + // start and end nodes belong to different subtrees + return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + } + } + if (start !== end) { + // start and end should be statements and parent should be either block or a source file + if (!isBlockLike(start.parent)) { + return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + } + var statements = []; + for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement === start || statements.length) { + var errors = checkNode(statement); + if (errors) { + return { errors: errors }; + } + statements.push(statement); + } + if (statement === end) { + break; + } + } + return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } 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; + // We have a single node (start) + var errors = checkRootNode(start) || checkNode(start); + if (errors) { + return { errors: errors }; } - var memberDeclaration = symbol.valueDeclaration; - var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - return; + // If our selection is the expression in an ExpressionStatement, expand + // the selection to include the enclosing Statement (this stops us + // from trying to care about the return value of the extracted function + // and eliminates double semicolon insertion in certain scenarios) + var range = ts.isStatement(start) + ? [start] + : start.parent && start.parent.kind === 210 /* ExpressionStatement */ + ? [start.parent] + : start; + return { targetRange: { range: range, facts: rangeFacts, declarations: declarations } }; + } + function createErrorResult(sourceFile, start, length, message) { + return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; + } + function checkRootNode(node) { + if (ts.isIdentifier(node)) { + return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; } - // 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); + return undefined; + } + function checkForStaticContext(nodeToCheck, containingClass) { + var current = nodeToCheck; + while (current !== containingClass) { + if (current.kind === 149 /* PropertyDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 146 /* Parameter */) { + var ctorOrMethod = ts.getContainingFunction(current); + if (ctorOrMethod.kind === 152 /* Constructor */) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 151 /* MethodDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + } + current = current.parent; } - switch (assignmentBinaryExpression.right.kind) { - case 186 /* FunctionExpression */: { - var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - copyComments(assignmentBinaryExpression, method); - return method; + } + // Verifies whether we can actually extract this node or not. + function checkNode(nodeToCheck) { + var PermittedJumps; + (function (PermittedJumps) { + PermittedJumps[PermittedJumps["None"] = 0] = "None"; + PermittedJumps[PermittedJumps["Break"] = 1] = "Break"; + PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; + PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + if (!ts.isStatement(nodeToCheck) && !(ts.isExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; + } + if (ts.isInAmbientContext(nodeToCheck)) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.CannotExtractAmbientBlock)]; + } + // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default) + var containingClass = ts.getContainingClass(nodeToCheck); + if (containingClass) { + checkForStaticContext(nodeToCheck, containingClass); + } + var errors; + var permittedJumps = 4 /* Return */; + var seenLabels; + visit(nodeToCheck); + return errors; + function visit(node) { + if (errors) { + // already found an error - can stop now + return true; } - 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; + if (ts.isDeclaration(node)) { + var declaringNode = (node.kind === 226 /* VariableDeclaration */) ? node.parent.parent : node; + if (ts.hasModifier(declaringNode, 1 /* Export */)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + return true; } - else { - var expression = arrowFunctionBody; - bodyBlock = ts.createBlock([ts.createReturn(expression)]); - } - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - copyComments(assignmentBinaryExpression, method); - return method; + declarations.push(node.symbol); } - default: { - // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { - return; - } - var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, - /*type*/ undefined, assignmentBinaryExpression.right); - copyComments(assignmentBinaryExpression.parent, prop); - return prop; + // Some things can't be extracted in certain situations + switch (node.kind) { + case 238 /* ImportDeclaration */: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + return true; + case 97 /* SuperKeyword */: + // For a super *constructor call*, we have to be extracting the entire class, + // but a super *method call* simply implies a 'this' reference + if (node.parent.kind === 181 /* CallExpression */) { + // Super constructor call + var containingClass_1 = ts.getContainingClass(node); + if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + return true; + } + } + else { + rangeFacts |= RangeFacts.UsesThis; + } + break; } + if (!node || ts.isFunctionLike(node) || ts.isClassLike(node)) { + switch (node.kind) { + case 228 /* FunctionDeclaration */: + case 229 /* ClassDeclaration */: + if (node.parent.kind === 265 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) { + // You cannot extract global declarations + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.FunctionWillNotBeVisibleInTheNewScope)); + } + break; + } + // do not dive into functions or classes + return false; + } + var savedPermittedJumps = permittedJumps; + if (node.parent) { + switch (node.parent.kind) { + case 211 /* IfStatement */: + if (node.parent.thenStatement === node || node.parent.elseStatement === node) { + // forbid all jumps inside thenStatement or elseStatement + permittedJumps = 0 /* None */; + } + break; + case 224 /* TryStatement */: + if (node.parent.tryBlock === node) { + // forbid all jumps inside try blocks + permittedJumps = 0 /* None */; + } + else if (node.parent.finallyBlock === node) { + // allow unconditional returns from finally blocks + permittedJumps = 4 /* Return */; + } + break; + case 260 /* CatchClause */: + if (node.parent.block === node) { + // forbid all jumps inside the block of catch clause + permittedJumps = 0 /* None */; + } + break; + case 257 /* CaseClause */: + if (node.expression !== node) { + // allow unlabeled break inside case clauses + permittedJumps |= 1 /* Break */; + } + break; + default: + if (ts.isIterationStatement(node.parent, /*lookInLabeledStatements*/ false)) { + if (node.parent.statement === node) { + // allow unlabeled break/continue inside loops + permittedJumps |= 1 /* Break */ | 2 /* Continue */; + } + } + break; + } + } + switch (node.kind) { + case 169 /* ThisType */: + case 99 /* ThisKeyword */: + rangeFacts |= RangeFacts.UsesThis; + break; + case 222 /* LabeledStatement */: + { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } + case 218 /* BreakStatement */: + case 217 /* ContinueStatement */: + { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } + else { + if (!(permittedJumps & (218 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } + case 191 /* AwaitExpression */: + rangeFacts |= RangeFacts.IsAsyncFunction; + break; + case 197 /* YieldExpression */: + rangeFacts |= RangeFacts.IsGenerator; + break; + case 219 /* ReturnStatement */: + if (permittedJumps & 4 /* Return */) { + rangeFacts |= RangeFacts.HasReturn; + } + else { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalReturnStatement)); + } + break; + default: + ts.forEachChild(node, visit); + break; + } + permittedJumps = savedPermittedJumps; } } } - function copyComments(sourceNode, targetNode) { - ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { - if (kind === 3 /* MultiLineCommentTrivia */) { - // Remove leading /* - pos += 2; - // Remove trailing */ - end -= 2; + extractMethod_1.getRangeToExtract = getRangeToExtract; + function isValidExtractionTarget(node) { + // Note that we don't use isFunctionLike because we don't want to put the extracted closure *inside* a method + return (node.kind === 228 /* FunctionDeclaration */) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + } + /** + * Computes possible places we could extract the function into. For example, + * you may be able to extract into a class method *or* local closure *or* namespace function, + * depending on what's in the extracted body. + */ + function collectEnclosingScopes(range) { + var current = isReadonlyArray(range.range) ? ts.firstOrUndefined(range.range) : range.range; + if (range.facts & RangeFacts.UsesThis) { + // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class + var containingClass = ts.getContainingClass(current); + if (containingClass) { + return [containingClass]; + } + } + var start = current; + var scopes = undefined; + while (current) { + // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. + // Walk up to the closest parent of a place where we can logically put a sibling: + // * Function declaration + // * Class declaration or expression + // * Module/namespace or source file + if (current !== start && isValidExtractionTarget(current)) { + (scopes = scopes || []).push(current); + } + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current && current.parent && current.parent.kind === 146 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLike(parent); }).parent; } else { - // Remove leading // - pos += 2; + current = current.parent; } - ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + } + return scopes; + } + extractMethod_1.collectEnclosingScopes = collectEnclosingScopes; + /** + * Given a piece of text to extract ('targetRange'), computes a list of possible extractions. + * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes + * or an error explaining why we can't extract into that scope. + */ + function getPossibleExtractions(targetRange, context, requestedChangesIndex) { + if (requestedChangesIndex === void 0) { requestedChangesIndex = undefined; } + var sourceFile = context.file; + if (targetRange === undefined) { + return undefined; + } + var scopes = collectEnclosingScopes(targetRange); + if (scopes === undefined) { + return undefined; + } + var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + var _a = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker()), target = _a.target, usagesPerScope = _a.usagesPerScope, errorsPerScope = _a.errorsPerScope; + context.cancellationToken.throwIfCancellationRequested(); + if (requestedChangesIndex !== undefined) { + if (errorsPerScope[requestedChangesIndex].length) { + return undefined; + } + return [extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context)]; + } + else { + return scopes.map(function (scope, i) { + var errors = errorsPerScope[i]; + if (errors.length) { + return { + scope: scope, + scopeDescription: getDescriptionForScope(scope), + errors: errors + }; + } + return { scope: scope, scopeDescription: getDescriptionForScope(scope) }; + }); + } + } + extractMethod_1.getPossibleExtractions = getPossibleExtractions; + function getDescriptionForScope(scope) { + if (ts.isFunctionLike(scope)) { + switch (scope.kind) { + case 152 /* Constructor */: + return "constructor"; + case 186 /* FunctionExpression */: + return scope.name + ? "function expression " + scope.name.getText() + : "anonymous function expression"; + case 228 /* FunctionDeclaration */: + return "function " + scope.name.getText(); + case 187 /* ArrowFunction */: + return "arrow function"; + case 151 /* MethodDeclaration */: + return "method " + scope.name.getText(); + case 153 /* GetAccessor */: + return "get " + scope.name.getText(); + case 154 /* SetAccessor */: + return "set " + scope.name.getText(); + } + } + else if (ts.isModuleBlock(scope)) { + return "namespace " + scope.parent.name.getText(); + } + else if (ts.isClassLike(scope)) { + return scope.kind === 229 /* ClassDeclaration */ + ? "class " + scope.name.text + : scope.name.text + ? "class expression " + scope.name.text + : "anonymous class expression"; + } + else if (ts.isSourceFile(scope)) { + return "file '" + scope.fileName + "'"; + } + else { + return "unknown"; + } + } + function getUniqueName(isNameOkay) { + var functionNameText = "newFunction"; + if (isNameOkay(functionNameText)) { + return functionNameText; + } + var i = 1; + while (!isNameOkay(functionNameText = "newFunction_" + i)) { + i++; + } + return functionNameText; + } + function extractFunctionInScope(node, scope, _a, range, context) { + var usagesInScope = _a.usages, substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted function + var file = scope.getSourceFile(); + var functionNameText = getUniqueName(function (n) { return !file.identifiers.has(n); }); + var isJS = ts.isInJavaScriptFile(scope); + var functionName = ts.createIdentifier(functionNameText); + var functionReference = ts.createIdentifier(functionNameText); + var returnType = undefined; + var parameters = []; + var callArguments = []; + var writes; + usagesInScope.forEach(function (usage, name) { + var typeNode = undefined; + if (!isJS) { + var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + type = checker.getBaseTypeOfLiteralType(type); + typeNode = checker.typeToTypeNode(type, node, ts.NodeBuilderFlags.NoTruncation); + } + var paramDecl = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ name, + /*questionToken*/ undefined, typeNode); + parameters.push(paramDecl); + if (usage.usage === 2 /* Write */) { + (writes || (writes = [])).push(usage); + } + callArguments.push(ts.createIdentifier(name)); }); + // Provide explicit return types for contexutally-typed functions + // to avoid problems when there are literal types present + if (ts.isExpression(node) && !isJS) { + var contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType); + } + var _b = transformFunctionBody(node), body = _b.body, returnValueProperty = _b.returnValueProperty; + var newFunction; + if (ts.isClassLike(scope)) { + // always create private method in TypeScript files + var modifiers = isJS ? [] : [ts.createToken(112 /* PrivateKeyword */)]; + if (range.facts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(115 /* StaticKeyword */)); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + modifiers.push(ts.createToken(120 /* AsyncKeyword */)); + } + newFunction = ts.createMethod( + /*decorators*/ undefined, modifiers, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, + /*questionToken*/ undefined, + /*typeParameters*/ [], parameters, returnType, body); + } + else { + newFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, + /*typeParameters*/ [], parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + // insert function at the end of the scope + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + var newNodes = []; + // replace range with function call + var call = ts.createCall(ts.isClassLike(scope) ? ts.createPropertyAccess(range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.getText()) : ts.createThis(), functionReference) : functionReference, + /*typeArguments*/ undefined, callArguments); + if (range.facts & RangeFacts.IsGenerator) { + call = ts.createYield(ts.createToken(39 /* AsteriskToken */), call); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + call = ts.createAwait(call); + } + if (writes) { + if (returnValueProperty) { + // has both writes and return, need to create variable declaration to hold return value; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119 /* AnyKeyword */))])); + } + var assignments = getPropertyAssignmentsForWrites(writes); + if (returnValueProperty) { + assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); + } + // propagate writes back + if (assignments.length === 1) { + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + else { + newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58 /* EqualsToken */, call))); + } + } + else { + // emit e.g. + // { a, b, __return } = newFunction(a, b); + // return __return; + newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58 /* EqualsToken */, call))); + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + } + } + else { + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn(call)); + } + else if (isReadonlyArray(range.range)) { + newNodes.push(ts.createStatement(call)); + } + else { + newNodes.push(call); + } + } + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { + nodeSeparator: context.newLineCharacter, + suffix: context.newLineCharacter // insert newline only when replacing statements + }); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); + } + return { + scope: scope, + scopeDescription: getDescriptionForScope(scope), + changes: changeTracker.getChanges() + }; + function getPropertyAssignmentsForWrites(writes) { + return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + } + function generateReturnValueProperty() { + return "__return"; + } + function transformFunctionBody(body) { + if (ts.isBlock(body) && !writes && substitutions.size === 0) { + // already block, no writes to propagate back, no substitutions - can use node as is + return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; + } + var returnValueProperty; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions + if (writes || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (writes && !(range.facts & RangeFacts.HasReturn) && ts.isStatement(body)) { + // add return at the end to propagate writes back in case if control flow falls out of the function body + // it is ok to know that range has at least one return since it we only allow unconditional returns + var assignments = getPropertyAssignmentsForWrites(writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; + } + function visitor(node) { + if (node.kind === 219 /* ReturnStatement */ && writes) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = generateReturnValueProperty(); + } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); + } + else { + return ts.createReturn(ts.createObjectLiteral(assignments)); + } + } + else { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } + } } - function createClassFromVariableDeclaration(node) { - var initializer = node.initializer; - if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { + extractMethod_1.extractFunctionInScope = extractFunctionInScope; + function isReadonlyArray(v) { + return ts.isArray(v); + } + /** + * Produces a range that spans the entirety of nodes, given a selection + * that might start/end in the middle of nodes. + * + * For example, when the user makes a selection like this + * v---v + * var someThing = foo + bar; + * this returns ^-------^ + */ + function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) + ? { pos: targetRange.range[0].getStart(sourceFile), end: targetRange.range[targetRange.range.length - 1].getEnd() } + : targetRange.range; + } + var Usage; + (function (Usage) { + // value should be passed to extracted method + Usage[Usage["Read"] = 1] = "Read"; + // value should be passed to extracted method and propagated back + Usage[Usage["Write"] = 2] = "Write"; + })(Usage || (Usage = {})); + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker) { + var usagesPerScope = []; + var substitutionsPerScope = []; + var errorsPerScope = []; + var visibleDeclarationsInExtractedRange = []; + // initialize results + for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { + var _ = scopes_1[_i]; + usagesPerScope.push({ usages: ts.createMap(), substitutions: ts.createMap() }); + substitutionsPerScope.push(ts.createMap()); + errorsPerScope.push([]); + } + var seenUsages = ts.createMap(); + var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); + collectUsages(target); + var _loop_8 = function (i) { + var hasWrite = false; + var readonlyClassPropertyWrite = undefined; + usagesPerScope[i].usages.forEach(function (value) { + if (value.usage === 2 /* Write */) { + hasWrite = true; + if (value.symbol.flags & 106500 /* ClassMember */ && + value.symbol.valueDeclaration && + ts.hasModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { + readonlyClassPropertyWrite = value.symbol.valueDeclaration; + } + } + }); + if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { + errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); + } + else if (readonlyClassPropertyWrite && i > 0) { + errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotCombineWritesAndReturns)); + } + }; + for (var i = 0; i < scopes.length; i++) { + _loop_8(i); + } + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + function collectUsages(node, valueUsage) { + if (valueUsage === void 0) { valueUsage = 1 /* Read */; } + if (ts.isDeclaration(node) && node.symbol) { + visibleDeclarationsInExtractedRange.push(node.symbol); + } + if (ts.isAssignmentExpression(node)) { + // use 'write' as default usage for values + collectUsages(node.left, 2 /* Write */); + collectUsages(node.right); + } + else if (ts.isUnaryExpressionWithWrite(node)) { + collectUsages(node.operand, 2 /* Write */); + } + else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { + // use 'write' as default usage for values + ts.forEachChild(node, collectUsages); + } + else if (ts.isIdentifier(node)) { + if (!node.parent) { + return; + } + if (ts.isQualifiedName(node.parent) && node !== node.parent.left) { + return; + } + if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { + return; + } + recordUsage(node, valueUsage, /*isTypeNode*/ ts.isPartOfTypeNode(node)); + } + else { + ts.forEachChild(node, collectUsages); + } + } + function recordUsage(n, usage, isTypeNode) { + var symbolId = recordUsagebySymbol(n, usage, isTypeNode); + if (symbolId) { + for (var i = 0; i < scopes.length; i++) { + // push substitution from map to map to simplify rewriting + var substitition = substitutionsPerScope[i].get(symbolId); + if (substitition) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitition); + } + } + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + var symbol = checker.getSymbolAtLocation(identifier); + if (!symbol) { + // cannot find symbol - do nothing + return undefined; + } + var symbolId = ts.getSymbolId(symbol).toString(); + var lastUsage = seenUsages.get(symbolId); + // there are two kinds of value usages + // - reads - if range contains a read from the value located outside of the range then value should be passed as a parameter + // - writes - if range contains a write to a value located outside the range the value should be passed as a parameter and + // returned as a return value + // 'write' case is a superset of 'read' so if we already have processed 'write' of some symbol there is not need to handle 'read' + // since all information is already recorded + if (lastUsage && lastUsage >= usage) { + return symbolId; + } + seenUsages.set(symbolId, usage); + if (lastUsage) { + // if we get here this means that we are trying to handle 'write' and 'read' was already processed + // walk scopes and update existing records. + for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) { + var perScope = usagesPerScope_1[_i]; + var prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) { + perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + return symbolId; + } + // find first declaration in this file + var declInFile = ts.find(symbol.getDeclarations(), function (d) { return d.getSourceFile() === sourceFile; }); + if (!declInFile) { + return undefined; + } + if (ts.rangeContainsRange(enclosingTextRange, declInFile)) { + // declaration is located in range to be extracted - do nothing + return undefined; + } + if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) { + // this is write to a reference located outside of the target scope and range is extracted into generator + // currently this is unsupported scenario + for (var _a = 0, errorsPerScope_1 = errorsPerScope; _a < errorsPerScope_1.length; _a++) { + var errors = errorsPerScope_1[_a]; + errors.push(ts.createDiagnosticForNode(identifier, Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators)); + } + } + for (var i = 0; i < scopes.length; i++) { + var scope = scopes[i]; + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + if (resolvedSymbol === symbol) { + continue; + } + if (!substitutionsPerScope[i].has(symbolId)) { + var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) { + substitutionsPerScope[i].set(symbolId, substitution); + } + else if (isTypeName) { + errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + } + else { + usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + } + return symbolId; + } + function checkForUsedDeclarations(node) { + // If this node is entirely within the original extraction range, we don't need to do anything. + if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) { + return; + } + // Otherwise check and recurse. + var sym = checker.getSymbolAtLocation(node); + if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { + for (var _i = 0, errorsPerScope_2 = errorsPerScope; _i < errorsPerScope_2.length; _i++) { + var scope = errorsPerScope_2[_i]; + scope.push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + } + return true; + } + else { + ts.forEachChild(node, checkForUsedDeclarations); + } + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { + if (!symbol) { + return undefined; + } + if (symbol.getDeclarations().some(function (d) { return d.parent === scopeDecl; })) { + return ts.createIdentifier(symbol.name); + } + var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); + if (prefix === undefined) { + return undefined; + } + return isTypeNode ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) : ts.createPropertyAccess(prefix, symbol.name); + } + } + function getParentNodeInSpan(node, file, span) { + if (!node) return undefined; + while (node.parent) { + if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) { + return node; + } + node = node.parent; } - 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)); - } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); - // Don't call copyComments here because we'll already leave them in place - return cls; } - function createClassFromFunctionDeclaration(node) { - var memberElements = createClassElementsFromSymbol(ctorSymbol); - if (node.body) { - memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); - } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); - // Don't call copyComments here because we'll already leave them in place - return cls; + function spanContainsNode(span, node, file) { + return ts.textSpanContainsPosition(span, node.getStart(file)) && + node.getEnd() <= ts.textSpanEnd(span); } - } + /** + * Computes whether or not a node represents an expression in a position where it could + * be extracted. + * The isExpression() in utilities.ts returns some false positives we need to handle, + * such as `import x from 'y'` -- the 'y' is a StringLiteral but is *not* an expression + * in the sense of something that you could extract on + */ + function isExtractableExpression(node) { + switch (node.parent.kind) { + case 264 /* EnumMember */: + return false; + } + switch (node.kind) { + case 9 /* StringLiteral */: + return node.parent.kind !== 238 /* ImportDeclaration */ && + node.parent.kind !== 242 /* ImportSpecifier */; + case 198 /* SpreadElement */: + case 174 /* ObjectBindingPattern */: + case 176 /* BindingElement */: + return false; + case 71 /* Identifier */: + return node.parent.kind !== 176 /* BindingElement */ && + node.parent.kind !== 242 /* ImportSpecifier */ && + node.parent.kind !== 246 /* ExportSpecifier */; + } + return true; + } + function isBlockLike(node) { + switch (node.kind) { + case 207 /* Block */: + case 265 /* SourceFile */: + case 234 /* ModuleBlock */: + case 257 /* CaseClause */: + return true; + default: + return false; + } + } + })(extractMethod = refactor.extractMethod || (refactor.extractMethod = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /// +/// /// /// /// @@ -89074,7 +90729,7 @@ var ts; node.parent = parent; return node; } - var NodeObject = (function () { + var NodeObject = /** @class */ (function () { function NodeObject(kind, pos, end) { this.pos = pos; this.end = end; @@ -89117,12 +90772,14 @@ var ts; ts.scanner.setTextPos(pos); while (pos < end) { var token = ts.scanner.scan(); - ts.Debug.assert(token !== 1 /* EndOfFileToken */); // Else it would infinitely loop var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); } pos = textPos; + if (token === 1 /* EndOfFileToken */) { + break; + } } return pos; }; @@ -89227,7 +90884,7 @@ var ts; }; return NodeObject; }()); - var TokenOrIdentifierObject = (function () { + var TokenOrIdentifierObject = /** @class */ (function () { function TokenOrIdentifierObject(pos, end) { // Set properties in same order as NodeObject this.pos = pos; @@ -89282,7 +90939,7 @@ var ts; }; return TokenOrIdentifierObject; }()); - var SymbolObject = (function () { + var SymbolObject = /** @class */ (function () { function SymbolObject(flags, name) { this.flags = flags; this.escapedName = name; @@ -89320,7 +90977,7 @@ var ts; }; return SymbolObject; }()); - var TokenObject = (function (_super) { + var TokenObject = /** @class */ (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { var _this = _super.call(this, pos, end) || this; @@ -89329,7 +90986,7 @@ var ts; } return TokenObject; }(TokenOrIdentifierObject)); - var IdentifierObject = (function (_super) { + var IdentifierObject = /** @class */ (function (_super) { __extends(IdentifierObject, _super); function IdentifierObject(_kind, pos, end) { return _super.call(this, pos, end) || this; @@ -89344,7 +91001,7 @@ var ts; return IdentifierObject; }(TokenOrIdentifierObject)); IdentifierObject.prototype.kind = 71 /* Identifier */; - var TypeObject = (function () { + var TypeObject = /** @class */ (function () { function TypeObject(checker, flags) { this.checker = checker; this.flags = flags; @@ -89386,7 +91043,7 @@ var ts; }; return TypeObject; }()); - var SignatureObject = (function () { + var SignatureObject = /** @class */ (function () { function SignatureObject(checker) { this.checker = checker; } @@ -89416,7 +91073,7 @@ var ts; }; return SignatureObject; }()); - var SourceFileObject = (function (_super) { + var SourceFileObject = /** @class */ (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { return _super.call(this, kind, pos, end) || this; @@ -89587,7 +91244,7 @@ var ts; }; return SourceFileObject; }(NodeObject)); - var SourceMapSourceObject = (function () { + var SourceMapSourceObject = /** @class */ (function () { function SourceMapSourceObject(fileName, text, skipTrivia) { this.fileName = fileName; this.text = text; @@ -89656,7 +91313,7 @@ var ts; // Cache host information about script Should be refreshed // at each language service public entry point, since we don't know when // the set of scripts handled by the host changes. - var HostCache = (function () { + var HostCache = /** @class */ (function () { function HostCache(host, getCanonicalFileName) { this.host = host; // script id => script index @@ -89718,7 +91375,7 @@ var ts; }; return HostCache; }()); - var SyntaxTreeCache = (function () { + var SyntaxTreeCache = /** @class */ (function () { function SyntaxTreeCache(host) { this.host = host; } @@ -89813,7 +91470,7 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - var CancellationTokenObject = (function () { + var CancellationTokenObject = /** @class */ (function () { function CancellationTokenObject(cancellationToken) { this.cancellationToken = cancellationToken; } @@ -89829,7 +91486,7 @@ var ts; }()); /* @internal */ /** A cancellation that throttles calls to the host */ - var ThrottledCancellationToken = (function () { + var ThrottledCancellationToken = /** @class */ (function () { function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) { if (throttleWaitMilliseconds === void 0) { throttleWaitMilliseconds = 20; } this.hostCancellationToken = hostCancellationToken; @@ -89980,8 +91637,8 @@ var ts; if (program) { var oldSourceFiles = program.getSourceFiles(); var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); } @@ -90038,7 +91695,7 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + path); + ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path); return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } // We didn't already have the file. Fall through and acquire it from the registry. @@ -90447,17 +92104,19 @@ var ts; function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var settings = toEditorSettings(options); - if (key === "{") { - return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + if (!ts.isInComment(sourceFile, position)) { + if (key === "{") { + return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "}") { + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === ";") { + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "\n") { + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + } } return []; } @@ -90504,6 +92163,11 @@ var ts; } return true; } + function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine); + return range && ts.createTextSpanFromRange(range); + } function getTodoComments(fileName, descriptors) { // Note: while getting todo comments seems like a syntactic operation, we actually // treat it as a semantic operation here. This is because we expect our host to call @@ -90693,6 +92357,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, @@ -90777,12 +92442,17 @@ var ts; function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(node.name)); - if (name && contextualType) { + return getPropertySymbolsFromType(contextualType, node.name); + } + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + /* @internal */ + function getPropertySymbolsFromType(type, propName) { + var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); + if (name && type) { var result_10 = []; - var symbol = contextualType.getProperty(name); - if (contextualType.flags & 65536 /* Union */) { - ts.forEach(contextualType.types, function (t) { + var symbol = type.getProperty(name); + if (type.flags & 65536 /* Union */) { + ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { result_10.push(symbol); @@ -90797,7 +92467,7 @@ var ts; } return undefined; } - ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + ts.getPropertySymbolsFromType = getPropertySymbolsFromType; function isArgumentOfElementAccessExpression(node) { return node && node.parent && @@ -91352,7 +93022,7 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 212 /* DoStatement */ || + if (node.parent.kind === 212 /* DoStatement */ || // Go to while keyword and do action instead node.parent.kind === 181 /* CallExpression */ || node.parent.kind === 182 /* NewExpression */) { return spanInPreviousNode(node); @@ -91471,7 +93141,7 @@ var ts; logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); } } - var ScriptSnapshotShimAdapter = (function () { + var ScriptSnapshotShimAdapter = /** @class */ (function () { function ScriptSnapshotShimAdapter(scriptSnapshotShim) { this.scriptSnapshotShim = scriptSnapshotShim; } @@ -91499,7 +93169,7 @@ var ts; }; return ScriptSnapshotShimAdapter; }()); - var LanguageServiceShimHostAdapter = (function () { + var LanguageServiceShimHostAdapter = /** @class */ (function () { function LanguageServiceShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; @@ -91623,7 +93293,7 @@ var ts; return LanguageServiceShimHostAdapter; }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; - var CoreServicesShimHostAdapter = (function () { + var CoreServicesShimHostAdapter = /** @class */ (function () { function CoreServicesShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; @@ -91688,7 +93358,7 @@ var ts; return JSON.stringify({ error: err }); } } - var ShimBase = (function () { + var ShimBase = /** @class */ (function () { function ShimBase(factory) { this.factory = factory; factory.registerShim(this); @@ -91712,7 +93382,7 @@ var ts; code: diagnostic.code }; } - var LanguageServiceShimObject = (function (_super) { + var LanguageServiceShimObject = /** @class */ (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { var _this = _super.call(this, factory) || this; @@ -91878,6 +93548,10 @@ var ts; var _this = this; return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); }); }; + LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) { + var _this = this; + return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); }); + }; /// GET SMART INDENT LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { var _this = this; @@ -91985,7 +93659,7 @@ var ts; function convertClassifications(classifications) { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } - var ClassifierShimObject = (function (_super) { + var ClassifierShimObject = /** @class */ (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { var _this = _super.call(this, factory) || this; @@ -92012,7 +93686,7 @@ var ts; }; return ClassifierShimObject; }(ShimBase)); - var CoreServicesShimObject = (function (_super) { + var CoreServicesShimObject = /** @class */ (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { var _this = _super.call(this, factory) || this; @@ -92119,7 +93793,7 @@ var ts; }; return CoreServicesShimObject; }(ShimBase)); - var TypeScriptServicesFactory = (function () { + var TypeScriptServicesFactory = /** @class */ (function () { function TypeScriptServicesFactory() { this._shims = []; } @@ -92200,4 +93874,6 @@ var TypeScript; // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "2.5"; +var toolsVersion = "2.6"; + +//# sourceMappingURL=typescriptServices.js.map diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 392b7e36a0..0b54986035 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -1210,7 +1210,7 @@ declare namespace ts { interface CatchClause extends Node { kind: SyntaxKind.CatchClause; parent?: TryStatement; - variableDeclaration: VariableDeclaration; + variableDeclaration?: VariableDeclaration; block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; @@ -1496,38 +1496,39 @@ declare namespace ts { interface FlowLock { locked?: boolean; } - interface AfterFinallyFlow extends FlowNode, FlowLock { + interface AfterFinallyFlow extends FlowNodeBase, FlowLock { antecedent: FlowNode; } - interface PreFinallyFlow extends FlowNode { + interface PreFinallyFlow extends FlowNodeBase { antecedent: FlowNode; lock: FlowLock; } - interface FlowNode { + type FlowNode = AfterFinallyFlow | PreFinallyFlow | FlowStart | FlowLabel | FlowAssignment | FlowCondition | FlowSwitchClause | FlowArrayMutation; + interface FlowNodeBase { flags: FlowFlags; id?: number; } - interface FlowStart extends FlowNode { + interface FlowStart extends FlowNodeBase { container?: FunctionExpression | ArrowFunction | MethodDeclaration; } - interface FlowLabel extends FlowNode { + interface FlowLabel extends FlowNodeBase { antecedents: FlowNode[]; } - interface FlowAssignment extends FlowNode { + interface FlowAssignment extends FlowNodeBase { node: Expression | VariableDeclaration | BindingElement; antecedent: FlowNode; } - interface FlowCondition extends FlowNode { + interface FlowCondition extends FlowNodeBase { expression: Expression; antecedent: FlowNode; } - interface FlowSwitchClause extends FlowNode { + interface FlowSwitchClause extends FlowNodeBase { switchStatement: SwitchStatement; clauseStart: number; clauseEnd: number; antecedent: FlowNode; } - interface FlowArrayMutation extends FlowNode { + interface FlowArrayMutation extends FlowNodeBase { node: CallExpression | BinaryExpression; antecedent: FlowNode; } @@ -1696,6 +1697,15 @@ declare namespace ts { getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + /** + * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. + * Otherwise returns its input. + * For example, at `export type T = number;`: + * - `getSymbolAtLocation` at the location `T` will return the exported symbol for `T`. + * - But the result of `getSymbolsInScope` will contain the *local* symbol for `T`, not the exported symbol. + * - Calling `getExportSymbolOfSymbol` on that local symbol will return the exported symbol. + */ + getExportSymbolOfSymbol(symbol: Symbol): Symbol; getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; @@ -1790,11 +1800,11 @@ declare namespace ts { UseFullyQualifiedType = 256, InFirstTypeArgument = 512, InTypeAlias = 1024, - UseTypeAliasValue = 2048, SuppressAnyReturnType = 4096, AddUndefined = 8192, WriteClassExpressionAsTypeLiteral = 16384, InArrayType = 32768, + UseAliasDefinedOutsideCurrentScope = 65536, } enum SymbolFormatFlags { None = 0, @@ -2056,6 +2066,7 @@ declare namespace ts { interface TypeVariable extends Type { } interface TypeParameter extends TypeVariable { + /** Retrieve using getConstraintFromTypeParameter */ constraint: Type; default?: Type; } @@ -2103,6 +2114,21 @@ declare namespace ts { NoDefault = 2, AnyDefault = 4, } + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ + enum Ternary { + False = 0, + Maybe = 1, + True = -1, + } + type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary; interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; @@ -2195,6 +2221,7 @@ declare namespace ts { outFile?: string; paths?: MapLike; preserveConstEnums?: boolean; + preserveSymlinks?: boolean; project?: string; reactNamespace?: string; jsxFactory?: string; @@ -2300,6 +2327,10 @@ declare namespace ts { readFile(fileName: string): string | undefined; trace?(s: string): void; directoryExists?(directoryName: string): boolean; + /** + * Resolve a symbolic link. + * @see https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options + */ realpath?(path: string): string; getCurrentDirectory?(): string; getDirectories?(path: string): string[]; @@ -2314,17 +2345,13 @@ declare namespace ts { interface ResolvedModule { /** Path of the file the module was resolved to. */ resolvedFileName: string; - /** - * Denotes if 'resolvedFileName' is isExternalLibraryImport and thus should be a proper external module: - * - be a .d.ts file - * - use top level imports\exports - * - don't use tripleslash references - */ + /** True if `resolvedFileName` comes from `node_modules`. */ isExternalLibraryImport?: boolean; } /** * ResolvedModule with an explicitly provided `extension` property. * Prefer this over `ResolvedModule`. + * If changing this, remember to change `moduleResolutionIsEqualTo`. */ interface ResolvedModuleFull extends ResolvedModule { /** @@ -2332,6 +2359,21 @@ declare namespace ts { * This is optional for backwards-compatibility, but will be added if not provided. */ extension: Extension; + packageId?: PackageId; + } + /** + * Unique identifier with a package name and version. + * If changing this, remember to change `packageIdIsEqual`. + */ + interface PackageId { + /** + * Name of the package. + * Should not include `@types`. + * If accessing a non-index file, this should include its name e.g. "foo/bar". + */ + name: string; + /** Version of the package, e.g. "1.2.3" */ + version: string; } enum Extension { Ts = ".ts", @@ -2593,7 +2635,7 @@ declare namespace ts { } } declare namespace ts { - const versionMajorMinor = "2.5"; + const versionMajorMinor = "2.6"; /** The version of the TypeScript compiler release */ const version: string; } @@ -2741,6 +2783,8 @@ declare namespace ts { function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: Node): boolean; + function isEmptyBindingPattern(node: BindingName): node is BindingPattern; + function isEmptyBindingElement(node: BindingElement): boolean; function getCombinedModifierFlags(node: Node): ModifierFlags; function getCombinedNodeFlags(node: Node): NodeFlags; /** @@ -3310,8 +3354,8 @@ declare namespace ts { function updateDefaultClause(node: DefaultClause, statements: ReadonlyArray): DefaultClause; function createHeritageClause(token: HeritageClause["token"], types: ReadonlyArray): HeritageClause; function updateHeritageClause(node: HeritageClause, types: ReadonlyArray): HeritageClause; - function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause; - function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; + function createCatchClause(variableDeclaration: string | VariableDeclaration | undefined, block: Block): CatchClause; + function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block): CatchClause; function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression): PropertyAssignment; function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression): ShorthandPropertyAssignment; @@ -3773,6 +3817,7 @@ declare namespace ts { getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; + getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index eb71a73ba4..f1356d558c 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -511,7 +511,7 @@ var ts; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); - var OperationCanceledException = (function () { + var OperationCanceledException = /** @class */ (function () { function OperationCanceledException() { } return OperationCanceledException; @@ -570,11 +570,12 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 2048] = "UseTypeAliasValue"; TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + // even though `T` can't be accessed in the current scope. })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -860,6 +861,21 @@ var ts; InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ var SpecialPropertyAssignmentKind; (function (SpecialPropertyAssignmentKind) { @@ -1329,27 +1345,12 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "2.5"; + ts.versionMajorMinor = "2.6"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); /* @internal */ (function (ts) { - /** - * Ternary values are defined such that - * x & y is False if either x or y is False. - * x & y is Maybe if either x or y is Maybe, but neither x or y is False. - * x & y is True if both x and y are True. - * x | y is False if both x and y are False. - * x | y is Maybe if either x or y is Maybe, but neither x or y is True. - * x | y is True if either x or y is True. - */ - var Ternary; - (function (Ternary) { - Ternary[Ternary["False"] = 0] = "False"; - Ternary[Ternary["Maybe"] = 1] = "Maybe"; - Ternary[Ternary["True"] = -1] = "True"; - })(Ternary = ts.Ternary || (ts.Ternary = {})); // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(/*locales*/ undefined, { usage: "sort", sensitivity: "accent" }) : undefined; // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". @@ -1403,7 +1404,7 @@ var ts; var MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); // Keep the class inside a function so it doesn't get compiled if it's not used. function shimMap() { - var MapIterator = (function () { + var MapIterator = /** @class */ (function () { function MapIterator(data, selector) { this.index = 0; this.data = data; @@ -1420,7 +1421,7 @@ var ts; }; return MapIterator; }()); - return (function () { + return /** @class */ (function () { function class_1() { this.data = createDictionaryObject(); this.size = 0; @@ -1668,10 +1669,9 @@ var ts; ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (f(item)) { - array[outIndex] = item; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; outIndex++; } } @@ -1722,8 +1722,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1799,11 +1799,13 @@ var ts; ts.sameFlatMap = sameFlatMap; function mapDefined(array, mapFn) { var result = []; - for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); - if (mapped !== undefined) { - result.push(mapped); + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } } } return result; @@ -1882,8 +1884,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; if (predicate(v)) { return true; } @@ -1909,8 +1911,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var item = array_6[_i]; + loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -2003,8 +2005,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var v = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; // Note: we need the following type assertion because of GH #17069 result += v[prop]; } @@ -2336,8 +2338,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var value = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -2502,11 +2504,11 @@ var ts; ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { var end = start + length; - Debug.assert(start >= 0, "start must be non-negative, is " + start); - Debug.assert(length >= 0, "length must be non-negative, is " + length); + Debug.assertGreaterThanOrEqual(start, 0); + Debug.assertGreaterThanOrEqual(length, 0); if (file) { - Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); - Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + Debug.assertLessThanOrEqual(start, file.text.length); + Debug.assertLessThanOrEqual(end, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -2736,19 +2738,23 @@ var ts; return normalized; } function normalizePath(path) { + return normalizePathAndParts(path).path; + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { path = normalizeSlashes(path); var rootLength = getRootLength(path); var root = path.substr(0, rootLength); - var normalized = getNormalizedParts(path, rootLength); - if (normalized.length) { - var joinedParts = root + normalized.join(ts.directorySeparator); - return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts; + var parts = getNormalizedParts(path, rootLength); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; } else { - return root; + return { path: root, parts: parts }; } } - ts.normalizePath = normalizePath; + ts.normalizePathAndParts = normalizePathAndParts; /** A path ending with '/' refers to a directory only, never a file. */ function pathEndsWithDirectorySeparator(path) { return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; @@ -3055,14 +3061,43 @@ var ts; // proof. var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - /** - * Matches any single directory segment unless it is the last segment and a .min.js file - * Breakdown: - * [^./] # matches everything up to the first . character (excluding directory seperators) - * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension - */ - var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; - var singleAsteriskRegexFragmentOther = "[^/]*"; + /* @internal */ + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + /** + * Matches any single directory segment unless it is the last segment and a .min.js file + * Breakdown: + * [^./] # matches everything up to the first . character (excluding directory seperators) + * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension + */ + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; function getRegularExpressionForWildcard(specs, basePath, usage) { var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); if (!patterns || !patterns.length) { @@ -3078,15 +3113,8 @@ var ts; if (specs === undefined || specs.length === 0) { return undefined; } - var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; - var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; - /** - * Regex for the ** wildcard. Matches any number of subdirectories. When used for including - * files or directories, does not match subdirectories that start with a . character - */ - var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; return flatMap(specs, function (spec) { - return spec && getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } /** @@ -3097,7 +3125,8 @@ var ts; return !/[.*?]/.test(lastPathComponent); } ts.isImplicitGlob = isImplicitGlob; - function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; @@ -3131,19 +3160,33 @@ var ts; subpattern += ts.directorySeparator; } if (usage !== "exclude") { + var componentPattern = ""; // The * and ? wildcards should not match directories or files that start with . if they // appear first in a component. Dotted directories and files can be included explicitly // like so: **/.*/.* if (component.charCodeAt(0) === 42 /* asterisk */) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; component = component.substr(1); } else if (component.charCodeAt(0) === 63 /* question */) { - subpattern += "[^./]"; + componentPattern += "[^./]"; component = component.substr(1); } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + // Patterns should not include subfolders like node_modules unless they are + // explicitly included as part of the path. + // + // As an optimization, if the component pattern is the same as the component, + // then there definitely were no wildcard characters and we do not need to + // add the exclusion pattern. + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } hasWrittenComponent = true; } @@ -3153,12 +3196,6 @@ var ts; } return subpattern; } - function replaceWildCardCharacterFiles(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); - } - function replaceWildCardCharacterOther(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); - } function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } @@ -3319,14 +3356,7 @@ var ts; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = allSupportedExtensions.slice(0); - for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { - var extInfo = extraFileExtensions_1[_i]; - if (extensions.indexOf(extInfo.extension) === -1) { - extensions.push(extInfo.extension); - } - } - return extensions; + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -3481,12 +3511,37 @@ var ts; function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { if (verboseDebugInfo) { - message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); } fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; function fail(message, stackCrawlMark) { debugger; var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); @@ -3652,6 +3707,10 @@ var ts; Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; function tryGetExtensionFromPath(path) { return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } @@ -3664,6 +3723,18 @@ var ts; /// var ts; (function (ts) { + /** + * Set a high stack trace limit to provide more information in case of an error. + * Called for command-line and server use cases. + * Not called if TypeScript is used as a library. + */ + /* @internal */ + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; var FileWatcherEventKind; (function (FileWatcherEventKind) { FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; @@ -3714,7 +3785,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -4569,6 +4640,8 @@ var ts; Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4756,6 +4829,7 @@ var ts; Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -5009,6 +5083,8 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), + Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), }; })(ts || (ts = {})); /// @@ -6812,19 +6888,6 @@ var ts; return undefined; } ts.getDeclarationOfKind = getDeclarationOfKind; - function findDeclaration(symbol, predicate) { - var declarations = symbol.declarations; - if (declarations) { - for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { - var declaration = declarations_2[_i]; - if (predicate(declaration)) { - return declaration; - } - } - } - return undefined; - } - ts.findDeclaration = findDeclaration; var stringWriter = createSingleLineStringWriter(); var stringWriterAcquired = false; function createSingleLineStringWriter() { @@ -6886,19 +6949,20 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; - /* @internal */ function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && - oldResolution.resolvedFileName === newResolution.resolvedFileName; + oldResolution.resolvedFileName === newResolution.resolvedFileName && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; - /* @internal */ + function packageIdIsEqual(a, b) { + return a === b || a && b && a.name === b.name && a.version === b.version; + } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; - /* @internal */ function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { ts.Debug.assert(names.length === newResolutions.length); for (var i = 0; i < names.length; i++) { @@ -6968,14 +7032,6 @@ var ts; return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; } ts.nodePosToString = nodePosToString; - function getStartPosOfNode(node) { - return node.pos; - } - ts.getStartPosOfNode = getStartPosOfNode; - function isDefined(value) { - return value !== undefined; - } - ts.isDefined = isDefined; function getEndLinePosition(line, sourceFile) { ts.Debug.assert(line >= 0); var lineStarts = ts.getLineStarts(sourceFile); @@ -7025,6 +7081,32 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (text.charCodeAt(commentPos + 1) === 47 /* slash */ && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47 /* slash */) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, comment) { + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + } + ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* // want to skip trivia because this will launch us forward to the next token. @@ -7094,15 +7176,20 @@ var ts; // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { case 9 /* StringLiteral */: - return '"' + escapeText(node.text) + '"'; + if (node.singleQuote) { + return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; + } + else { + return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + } case 13 /* NoSubstitutionTemplateLiteral */: - return "`" + escapeText(node.text) + "`"; + return "`" + escapeText(node.text, 96 /* backtick */) + "`"; case 14 /* TemplateHead */: - return "`" + escapeText(node.text) + "${"; + return "`" + escapeText(node.text, 96 /* backtick */) + "${"; case 15 /* TemplateMiddle */: - return "}" + escapeText(node.text) + "${"; + return "}" + escapeText(node.text, 96 /* backtick */) + "${"; case 16 /* TemplateTail */: - return "}" + escapeText(node.text) + "`"; + return "}" + escapeText(node.text, 96 /* backtick */) + "`"; case 8 /* NumericLiteral */: return node.text; } @@ -7191,6 +7278,7 @@ var ts; return ts.isExternalModule(node) || compilerOptions.isolatedModules; } ts.isEffectiveExternalModule = isEffectiveExternalModule; + /* @internal */ function isBlockScope(node, parentNode) { switch (node.kind) { case 265 /* SourceFile */: @@ -7381,13 +7469,9 @@ var ts; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); + return node.kind !== 10 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; - function getLeadingCommentRangesOfNodeFromText(node, text) { - return ts.getLeadingCommentRanges(text, node.pos); - } - ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; function getJSDocCommentRanges(node, text) { var commentRanges = (node.kind === 146 /* Parameter */ || node.kind === 145 /* TypeParameter */ || @@ -7395,7 +7479,7 @@ var ts; node.kind === 187 /* ArrowFunction */ || node.kind === 185 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : - getLeadingCommentRangesOfNodeFromText(node, text); + ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' return ts.filter(commentRanges, function (comment) { return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && @@ -7405,8 +7489,9 @@ var ts; } ts.getJSDocCommentRanges = getJSDocCommentRanges; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; - ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { if (158 /* FirstTypeNode */ <= node.kind && node.kind <= 173 /* LastTypeNode */) { return true; @@ -7660,21 +7745,11 @@ var ts; } ts.getPropertyAssignment = getPropertyAssignment; function getContainingFunction(node) { - while (true) { - node = node.parent; - if (!node || ts.isFunctionLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isFunctionLike); } ts.getContainingFunction = getContainingFunction; function getContainingClass(node) { - while (true) { - node = node.parent; - if (!node || ts.isClassLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isClassLike); } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { @@ -8570,14 +8645,14 @@ var ts; ts.getAncestor = getAncestor; function getFileReferenceFromReferencePath(comment, commentRange) { var simpleReferenceRegEx = /^\/\/\/\s*/gim; + var isNoDefaultLibRegEx = new RegExp(defaultLibReferenceRegEx.source, "gim"); if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); - var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); + var refLibResult = !refMatchResult && fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); var match = refMatchResult || refLibResult; if (match) { var pos = commentRange.pos + match[1].length + match[2].length; @@ -8782,10 +8857,6 @@ var ts; return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } ts.getOriginalSourceFile = getOriginalSourceFile; - function getOriginalSourceFiles(sourceFiles) { - return ts.sameMap(sourceFiles, getOriginalSourceFile); - } - ts.getOriginalSourceFiles = getOriginalSourceFiles; var Associativity; (function (Associativity) { Associativity[Associativity["Left"] = 0] = "Left"; @@ -9029,7 +9100,9 @@ var ts; // the language service. These characters should be escaped when printing, and if any characters are added, // the map below must be updated. Note that this regexp *does not* include the 'delete' character. // There is no reason for this other than that JSON.stringify does not handle it either. - var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\0": "\\0", "\t": "\\t", @@ -9040,6 +9113,8 @@ var ts; "\n": "\\n", "\\": "\\\\", "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" // nextLine @@ -9049,7 +9124,10 @@ var ts; * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) * Note that this doesn't actually wrap the input in double quotes. */ - function escapeString(s) { + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; return s.replace(escapedCharsRegExp, getReplacement); } ts.escapeString = escapeString; @@ -9069,8 +9147,8 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiString(s) { - s = escapeString(s); + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. return nonAsciiCharacters.test(s) ? @@ -9455,7 +9533,7 @@ var ts; // // var x = 10; if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); } } else { @@ -9495,9 +9573,8 @@ var ts; } } return currentDetachedCommentInfo; - function isPinnedComment(comment) { - return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment); } } ts.emitDetachedComments = emitDetachedComments; @@ -9593,9 +9670,13 @@ var ts; } ts.hasModifiers = hasModifiers; function hasModifier(node, flags) { - return (getModifierFlags(node) & flags) !== 0; + return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; function getModifierFlags(node) { if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; @@ -9673,23 +9754,6 @@ var ts; return false; } ts.isDestructuringAssignment = isDestructuringAssignment; - // Returns false if this heritage clause element's expression contains something unsupported - // (i.e. not a name or dotted name). - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 71 /* Identifier */) { - return true; - } - else if (ts.isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } - } function isExpressionWithTypeArgumentsInClassExtendsClause(node) { return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } @@ -9816,78 +9880,6 @@ var ts; return carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; - /** - * Tests whether a node and its subtree is simple enough to have its position - * information ignored when emitting source maps in a destructuring assignment. - * - * @param node The expression to test. - */ - function isSimpleExpression(node) { - return isSimpleExpressionWorker(node, 0); - } - ts.isSimpleExpression = isSimpleExpression; - function isSimpleExpressionWorker(node, depth) { - if (depth <= 5) { - var kind = node.kind; - if (kind === 9 /* StringLiteral */ - || kind === 8 /* NumericLiteral */ - || kind === 12 /* RegularExpressionLiteral */ - || kind === 13 /* NoSubstitutionTemplateLiteral */ - || kind === 71 /* Identifier */ - || kind === 99 /* ThisKeyword */ - || kind === 97 /* SuperKeyword */ - || kind === 101 /* TrueKeyword */ - || kind === 86 /* FalseKeyword */ - || kind === 95 /* NullKeyword */) { - return true; - } - else if (kind === 179 /* PropertyAccessExpression */) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 180 /* ElementAccessExpression */) { - return isSimpleExpressionWorker(node.expression, depth + 1) - && isSimpleExpressionWorker(node.argumentExpression, depth + 1); - } - else if (kind === 192 /* PrefixUnaryExpression */ - || kind === 193 /* PostfixUnaryExpression */) { - return isSimpleExpressionWorker(node.operand, depth + 1); - } - else if (kind === 194 /* BinaryExpression */) { - return node.operatorToken.kind !== 40 /* AsteriskAsteriskToken */ - && isSimpleExpressionWorker(node.left, depth + 1) - && isSimpleExpressionWorker(node.right, depth + 1); - } - else if (kind === 195 /* ConditionalExpression */) { - return isSimpleExpressionWorker(node.condition, depth + 1) - && isSimpleExpressionWorker(node.whenTrue, depth + 1) - && isSimpleExpressionWorker(node.whenFalse, depth + 1); - } - else if (kind === 190 /* VoidExpression */ - || kind === 189 /* TypeOfExpression */ - || kind === 188 /* DeleteExpression */) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 177 /* ArrayLiteralExpression */) { - return node.elements.length === 0; - } - else if (kind === 178 /* ObjectLiteralExpression */) { - return node.properties.length === 0; - } - else if (kind === 181 /* CallExpression */) { - if (!isSimpleExpressionWorker(node.expression, depth + 1)) { - return false; - } - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (!isSimpleExpressionWorker(argument, depth + 1)) { - return false; - } - } - return true; - } - } - return false; - } /** * Formats an enum value as a string for debugging and debug assertions. */ @@ -9959,24 +9951,6 @@ var ts; return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true); } ts.formatObjectFlags = formatObjectFlags; - function getRangePos(range) { - return range ? range.pos : -1; - } - ts.getRangePos = getRangePos; - function getRangeEnd(range) { - return range ? range.end : -1; - } - ts.getRangeEnd = getRangeEnd; - /** - * Increases (or decreases) a position by the provided amount. - * - * @param pos The position. - * @param value The delta. - */ - function movePos(pos, value) { - return ts.positionIsSynthesized(pos) ? -1 : pos + value; - } - ts.movePos = movePos; /** * Creates a new TextRange from the provided pos and end. * @@ -10034,26 +10008,6 @@ var ts; return range.pos === range.end; } ts.isCollapsedRange = isCollapsedRange; - /** - * Creates a new TextRange from a provided range with its end position collapsed to its - * start position. - * - * @param range A TextRange. - */ - function collapseRangeToStart(range) { - return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); - } - ts.collapseRangeToStart = collapseRangeToStart; - /** - * Creates a new TextRange from a provided range with its start position collapsed to its - * end position. - * - * @param range A TextRange. - */ - function collapseRangeToEnd(range) { - return isCollapsedRange(range) ? range : moveRangePos(range, range.end); - } - ts.collapseRangeToEnd = collapseRangeToEnd; /** * Creates a new TextRange for a token at the provides start position. * @@ -10116,31 +10070,6 @@ var ts; function isInitializedVariable(node) { return node.initializer !== undefined; } - /** - * Gets a value indicating whether a node is merged with a class declaration in the same scope. - */ - function isMergedWithClass(node) { - if (node.symbol) { - for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 229 /* ClassDeclaration */ && declaration !== node) { - return true; - } - } - } - return false; - } - ts.isMergedWithClass = isMergedWithClass; - /** - * Gets a value indicating whether a node is the first declaration of its kind. - * - * @param node A Declaration node. - * @param kind The SyntaxKind to find among related declarations. - */ - function isFirstDeclarationOfKind(node, kind) { - return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; - } - ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; function isWatchSet(options) { // Firefox has Object.prototype.watch return options.watch && options.hasOwnProperty("watch"); @@ -10434,6 +10363,20 @@ var ts; return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 152 /* Constructor */ && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { while (node && (node.kind === 176 /* BindingElement */ || ts.isBindingPattern(node))) { node = node.parent; @@ -11618,6 +11561,19 @@ var ts; return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + /* @internal */ + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 193 /* PostfixUnaryExpression */: + return true; + case 192 /* PrefixUnaryExpression */: + return expr.operator === 43 /* PlusPlusToken */ || + expr.operator === 44 /* MinusMinusToken */; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; function isExpressionKind(kind) { return kind === 195 /* ConditionalExpression */ || kind === 197 /* YieldExpression */ @@ -11824,9 +11780,19 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 207 /* Block */; + || isBlockStatement(node); } ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 207 /* Block */) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 224 /* TryStatement */ || node.parent.kind === 260 /* CatchClause */) { + return false; + } + } + return !ts.isFunctionBlock(node); + } // Module references /* @internal */ function isModuleReference(node) { @@ -14207,11 +14173,31 @@ var ts; var node = parseTokenNode(); return token() === 23 /* DotToken */ ? undefined : node; } - function parseLiteralTypeNode() { + function parseLiteralTypeNode(negative) { var node = createNode(173 /* LiteralType */); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(192 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 38 /* MinusToken */; + nextToken(); + } + var expression; + switch (token()) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + expression = parseLiteralLikeNode(token()); + break; + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + expression = parseTokenNode(); + } + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); } function nextTokenIsNumericLiteral() { return nextToken() === 8 /* NumericLiteral */; @@ -14244,7 +14230,7 @@ var ts; case 86 /* FalseKeyword */: return parseLiteralTypeNode(); case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); case 105 /* VoidKeyword */: case 95 /* NullKeyword */: return parseTokenNode(); @@ -14293,6 +14279,7 @@ var ts; case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 134 /* ObjectKeyword */: + case 39 /* AsteriskToken */: return true; case 38 /* MinusToken */: return lookAhead(nextTokenIsNumericLiteral); @@ -14721,7 +14708,7 @@ var ts; // Didn't appear to actually be a parenthesized arrow function. Just bail out. return undefined; } - var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256 /* Async */); + var isAsync = ts.hasModifier(arrowFunction, 256 /* Async */); // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. var lastToken = token(); @@ -14879,7 +14866,7 @@ var ts; function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(187 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); - var isAsync = (ts.getModifierFlags(node) & 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -15890,7 +15877,7 @@ var ts; parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; - var isAsync = (ts.getModifierFlags(node) & 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -16132,10 +16119,14 @@ var ts; function parseCatchClause() { var result = createNode(260 /* CatchClause */); parseExpected(74 /* CatchKeyword */); - if (parseExpected(19 /* OpenParenToken */)) { + if (parseOptional(19 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); + parseExpected(20 /* CloseParenToken */); + } + else { + // Keep shape of node to avoid degrading performance. + result.variableDeclaration = undefined; } - parseExpected(20 /* CloseParenToken */); result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); return finishNode(result); } @@ -17036,8 +17027,8 @@ var ts; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; - if (identifier || - token() === 39 /* AsteriskToken */ || + if (identifier || // import id + token() === 39 /* AsteriskToken */ || // import * token() === 17 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(140 /* FromKeyword */); @@ -17345,7 +17336,7 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseIsolatedJSDocComment(content, start, length) { initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); - sourceFile = { languageVariant: 0 /* Standard */, text: content }; + sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); @@ -18093,8 +18084,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -18231,8 +18222,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -19201,40 +19192,23 @@ var ts; return antecedent; } setFlowNodeReferenced(antecedent); - return { - flags: flags, - expression: expression, - antecedent: antecedent - }; + return { flags: flags, expression: expression, antecedent: antecedent }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); - return { - flags: 128 /* SwitchClause */, - switchStatement: switchStatement, - clauseStart: clauseStart, - clauseEnd: clauseEnd, - antecedent: antecedent - }; + return { flags: 128 /* SwitchClause */, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { setFlowNodeReferenced(antecedent); - return { - flags: 16 /* Assignment */, - antecedent: antecedent, - node: node - }; + return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; } function createFlowArrayMutation(antecedent, node) { setFlowNodeReferenced(antecedent); - return { - flags: 256 /* ArrayMutation */, - antecedent: antecedent, - node: node - }; + var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; + return res; } function finishFlowLabel(flow) { var antecedents = flow.antecedents; @@ -20956,7 +20930,6 @@ var ts; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); var name = node.name; var initializer = node.initializer; var dotDotDotToken = node.dotDotDotToken; @@ -20969,7 +20942,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. - if (modifierFlags & 92 /* ParameterPropertyModifier */) { + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; } // parameters with object rest destructuring are ES Next syntax @@ -21006,8 +20979,7 @@ var ts; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 2 /* Ambient */) { + if (ts.hasModifier(node, 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. transformFlags = 3 /* AssertTypeScript */; } @@ -21068,7 +21040,10 @@ var ts; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + if (!node.variableDeclaration) { + transformFlags |= 8 /* AssertESNext */; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -21283,10 +21258,9 @@ var ts; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; - var modifierFlags = ts.getModifierFlags(node); var declarationListTransformFlags = node.declarationList.transformFlags; // An ambient declaration is TypeScript syntax. - if (modifierFlags & 2 /* Ambient */) { + if (ts.hasModifier(node, 2 /* Ambient */)) { transformFlags = 3 /* AssertTypeScript */; } else { @@ -21634,6 +21608,176 @@ var ts; ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); } })(ts || (ts = {})); +/** @internal */ +var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = ts.createMap(); // Key is id as string + var visitedSymbols = ts.createMap(); // Key is id as string + return { + walkType: function (type) { + visitedTypes.clear(); + visitedSymbols.clear(); + visitType(type); + return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + }, + walkSymbol: function (symbol) { + visitedTypes.clear(); + visitedSymbols.clear(); + visitSymbol(symbol); + return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + }, + }; + function visitType(type) { + if (!type) { + return; + } + var typeIdString = type.id.toString(); + if (visitedTypes.has(typeIdString)) { + return; + } + visitedTypes.set(typeIdString, type); + // Reuse visitSymbol to visit the type's symbol, + // but be sure to bail on recuring into the type if accept declines the symbol. + var shouldBail = visitSymbol(type.symbol); + if (shouldBail) + return; + // Visit the type's related types, if any + if (type.flags & 32768 /* Object */) { + var objectType = type; + var objectFlags = objectType.objectFlags; + if (objectFlags & 4 /* Reference */) { + visitTypeReference(type); + } + if (objectFlags & 32 /* Mapped */) { + visitMappedType(type); + } + if (objectFlags & (1 /* Class */ | 2 /* Interface */)) { + visitInterfaceType(type); + } + if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) { + visitObjectType(objectType); + } + } + if (type.flags & 16384 /* TypeParameter */) { + visitTypeParameter(type); + } + if (type.flags & 196608 /* UnionOrIntersection */) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 262144 /* Index */) { + visitIndexType(type); + } + if (type.flags & 524288 /* IndexedAccess */) { + visitIndexedAccessType(type); + } + } + function visitTypeList(types) { + if (!types) { + return; + } + for (var i = 0; i < types.length; i++) { + visitType(types[i]); + } + } + function visitTypeReference(type) { + visitType(type.target); + visitTypeList(type.typeArguments); + } + function visitTypeParameter(type) { + visitType(getConstraintFromTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + visitTypeList(type.types); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + if (signature.typePredicate) { + visitType(signature.typePredicate.type); + } + visitTypeList(signature.typeParameters); + for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + visitTypeList(interfaceT.typeParameters); + visitTypeList(getBaseTypes(interfaceT)); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */); + visitType(stringIndexType); + var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */); + visitType(numberIndexType); + // The two checks above *should* have already resolved the type (if needed), so this should be cached + var resolved = resolveStructuredTypeMembers(type); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + visitSignature(signature); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + visitSignature(signature); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return; + } + var symbolIdString = ts.getSymbolId(symbol).toString(); + if (visitedSymbols.has(symbolIdString)) { + return; + } + visitedSymbols.set(symbolIdString, symbol); + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); // Should handle members on classes and such + if (symbol.flags & 1952 /* HasExports */) { + symbol.exports.forEach(visitSymbol); + } + ts.forEach(symbol.declarations, function (d) { + // Type queries are too far resolved when we just visit the symbol's type + // (their type resolved directly to the member deeply referenced) + // So to get the intervening symbols, we need to check if there's a type + // query node on any of the symbol's declarations and get symbols there + if (d.type && d.type.kind === 162 /* TypeQuery */) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); /// /// var ts; @@ -21647,6 +21791,12 @@ var ts; return compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(/*packageId*/ undefined, r); + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -21667,13 +21817,12 @@ var ts; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); + function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { if (!ts.hasProperty(jsonContent, fieldName)) { @@ -21778,7 +21927,9 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - resolved = realpath(resolved, host, traceEnabled); + if (!options.preserveSymlinks) { + resolved = realPath(resolved, host, traceEnabled); + } if (traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); } @@ -22182,7 +22333,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension }; + return { path: path_1, extension: extension, packageId: undefined }; } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -22209,7 +22360,7 @@ var ts; 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(", ")); + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } @@ -22235,17 +22386,24 @@ var ts; trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks) { + resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); - return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); + // Treat explicit "node_modules" import as an external library import. + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } } } - function realpath(path, host, traceEnabled) { + function realPath(path, host, traceEnabled) { if (!host.realpath) { return path; } @@ -22271,7 +22429,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return resolvedFromFile; + return noPackageId(resolvedFromFile); } } if (!onlyRecordFailures) { @@ -22291,6 +22449,9 @@ var ts; return !host.directoryExists || host.directoryExists(directoryName); } ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. @@ -22329,9 +22490,9 @@ var ts; case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); } - function tryExtension(extension) { - var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, extension: extension }; + function tryExtension(ext) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, ext: ext }; } } /** Return the file if it exists. */ @@ -22355,12 +22516,20 @@ var ts; function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + var packageId; if (considerPackageJson) { var packageJsonPath = pathToPackageJson(candidate); if (directoryExists && state.host.fileExists(packageJsonPath)) { - var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var jsonContent = readJson(packageJsonPath, state.host); + if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { + packageId = { name: jsonContent.name, version: jsonContent.version }; + } + var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); if (fromPackageJson) { - return fromPackageJson; + return withPackageId(packageId, fromPackageJson); } } else { @@ -22371,13 +22540,10 @@ var ts; failedLookupLocations.push(packageJsonPath); } } - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } - function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); if (!file) { return undefined; } @@ -22395,12 +22561,17 @@ var ts; // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); + var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); + if (result) { + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + ts.Debug.assert(result.packageId === undefined); + return { path: result.path, ext: result.extension }; + } } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { - var extension = ts.tryGetExtensionFromPath(path); - return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; } /** True if `extension` is one of the supported `extensions`. */ function extensionIsOk(extensions, extension) { @@ -22418,7 +22589,7 @@ var ts; } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { @@ -22497,7 +22668,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); } - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -22508,7 +22679,7 @@ var ts; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -22521,7 +22692,7 @@ var ts; return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; @@ -22533,7 +22704,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); } } } @@ -22578,6 +22749,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /* @internal */ var ts; (function (ts) { @@ -22705,6 +22877,9 @@ var ts; node = ts.getParseTreeNode(node, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, + getExportSymbolOfSymbol: function (symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, getTypeAtLocation: function (node) { node = ts.getParseTreeNode(node); return node ? getTypeOfNode(node) : unknownType; @@ -22767,6 +22942,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); @@ -22789,11 +22965,10 @@ var ts; getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, getBaseConstraintOfType: getBaseConstraintOfType, - getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, - resolveNameAtLocation: function (location, name, meaning) { - location = ts.getParseTreeNode(location); - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, ts.escapeLeadingUnderscores(name)); + resolveName: function (name, location, meaning) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); }, + getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -23324,12 +23499,17 @@ var ts; // 2. inside a function // 3. inside an instance property initializer, a reference to a non-instance property // 4. inside a static property initializer, a reference to a static method in the same class + // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) // or if usage is in a type context: // 1. inside a type query (typeof in type position) - if (usage.parent.kind === 246 /* ExportSpecifier */) { + if (usage.parent.kind === 246 /* ExportSpecifier */ || (usage.parent.kind === 243 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } + // When resolving symbols for exports, the `usage` location passed in can be the export site directly + if (usage.kind === 243 /* ExportAssignment */ && usage.isExportEquals) { + return true; + } var container = ts.getEnclosingBlockScopeContainer(declaration); return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { @@ -23360,13 +23540,13 @@ var ts; current.parent.kind === 149 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { - if (ts.getModifierFlags(current.parent) & 32 /* Static */) { + if (ts.hasModifier(current.parent, 32 /* Static */)) { if (declaration.kind === 151 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 149 /* PropertyDeclaration */ && !(ts.getModifierFlags(declaration) & 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 149 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -23480,7 +23660,7 @@ var ts; // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -23499,7 +23679,7 @@ var ts; result = undefined; break; } - if (lastLocation && ts.getModifierFlags(lastLocation) & 32 /* Static */) { + if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type // parameter list is associated, with the exception of static member declarations in classes. @@ -23516,6 +23696,18 @@ var ts; } } break; + case 201 /* ExpressionWithTypeArguments */: + // The type parameters of a class are not in scope in the base class expression. + if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { + var container = location.parent.parent; + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 793064 /* Type */))) { + if (nameNotFoundMessage) { + error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return undefined; + } + } + break; // It is not legal to reference a class's own type parameters from a computed property name that // belongs to the class. For example: // @@ -23585,7 +23777,10 @@ var ts; lastLocation = location; location = location.parent; } - if (result && nameNotFoundMessage && noUnusedIdentifiers) { + // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. + // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. + // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. + if (result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { result.isReferenced = true; } if (!result) { @@ -23684,7 +23879,7 @@ var ts; } // No static member is present. // Check if we're in an instance method and look for a relevant instance member. - if (location === container && !(ts.getModifierFlags(location) & 32 /* Static */)) { + if (location === container && !ts.hasModifier(location, 32 /* Static */)) { var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); @@ -24130,7 +24325,6 @@ var ts; if (ambientModule) { return ambientModule; } - var isRelative = ts.isExternalModuleNameRelative(moduleReference); var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); @@ -24152,7 +24346,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule && resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -24186,7 +24380,7 @@ var ts; // An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, // and an external module with no 'export =' declaration resolves to the module itself. function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias)) || moduleSymbol; } // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may @@ -24199,7 +24393,7 @@ var ts; return symbol; } function hasExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports.get("export=") !== undefined; + return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; } function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); @@ -24461,7 +24655,7 @@ var ts; if (symbolFromSymbolTable.flags & 2097152 /* Alias */ && symbolFromSymbolTable.escapedName !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) { - if (!useOnlyExternalAliasing || + if (!useOnlyExternalAliasing || // We can use any type of alias to get the name // Is this external alias, then use it to name ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); @@ -24526,6 +24720,10 @@ var ts; } return false; } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -24608,7 +24806,7 @@ var ts; // because these kind of aliases can be used to name types in declaration file var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(ts.getModifierFlags(anyImportSyntax) & 1 /* Export */) && + !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export isDeclarationVisible(anyImportSyntax.parent)) { // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time @@ -24817,8 +25015,7 @@ var ts; // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (!inTypeAlias && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); @@ -24900,10 +25097,10 @@ var ts; return createTypeNodeFromObjectType(type); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || + (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; })); @@ -24914,10 +25111,8 @@ var ts; } } function createTypeNodeFromObjectType(type) { - if (type.objectFlags & 32 /* Mapped */) { - if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { - return createMappedTypeNodeFromType(type); - } + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -25505,7 +25700,7 @@ var ts; buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } else if (!(flags & 1024 /* InTypeAlias */) && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + ((flags & 65536 /* UseAliasDefinedOutsideCurrentScope */) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); } @@ -25667,9 +25862,7 @@ var ts; if (!symbolStack) { symbolStack = []; } - var isConstructorObject = type.flags & 32768 /* Object */ && - getObjectFlags(type) & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & 32 /* Class */; + var isConstructorObject = type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; if (isConstructorObject) { writeLiteralType(type, flags); } @@ -25685,17 +25878,17 @@ var ts; writeLiteralType(type, flags); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { + (symbol.parent || // is exported function symbol + ts.some(symbol.declarations, function (declaration) { return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return !!(flags & 4 /* UseTypeOfFunction */) || - (ts.contains(symbolStack, symbol)); // it is type of the symbol uses itself recursively + return !!(flags & 4 /* UseTypeOfFunction */) || // use typeof if format flags specify it + ts.contains(symbolStack, symbol); // it is type of the symbol uses itself recursively } } } @@ -25733,11 +25926,9 @@ var ts; return false; } function writeLiteralType(type, flags) { - if (type.objectFlags & 32 /* Mapped */) { - if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { - writeMappedType(type); - return; - } + if (isGenericMappedType(type)) { + writeMappedType(type); + return; } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -26113,7 +26304,7 @@ var ts; case 154 /* SetAccessor */: case 151 /* MethodDeclaration */: case 150 /* MethodSignature */: - if (ts.getModifierFlags(node) & (8 /* Private */ | 16 /* Protected */)) { + if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } @@ -26910,8 +27101,8 @@ var ts; // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set // in-place and returns the same array. function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; @@ -27055,7 +27246,7 @@ var ts; return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + type.resolvedBaseTypes = ts.emptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); if (!(baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 1 /* Any */))) { return; @@ -27104,12 +27295,7 @@ var ts; error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); return; } - if (type.resolvedBaseTypes === ts.emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } + type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type) { // An unapplied type parameter has its symbol still the same as the matching argument symbol. @@ -27221,7 +27407,9 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var declaration = ts.findDeclaration(symbol, function (d) { return d.kind === 283 /* JSDocTypedefTag */ || d.kind === 231 /* TypeAliasDeclaration */; }); + var declaration = ts.find(symbol.declarations, function (d) { + return d.kind === 283 /* JSDocTypedefTag */ || d.kind === 231 /* TypeAliasDeclaration */; + }); var type = getTypeFromTypeNode(declaration.kind === 283 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type); if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -27753,17 +27941,12 @@ var ts; else { // Combinations of function, class, enum and module var members = emptySymbols; - var constructSignatures = ts.emptyArray; var stringIndexInfo = undefined; if (symbol.exports) { members = getExportsOfSymbol(symbol); } if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); - constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); - if (!constructSignatures.length) { - constructSignatures = getDefaultConstructSignatures(classType); - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 540672 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); @@ -27774,7 +27957,7 @@ var ts; } } var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; - setStructuredTypeMembers(type, members, ts.emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); // We resolve the members before computing the signatures because a signature may use // typeof with a qualified name expression that circularly references the type we are // in the process of resolving (see issue #6072). The temporarily empty signature list @@ -27782,6 +27965,15 @@ var ts; if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); } + // And likewise for construct signatures for classes + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } } } /** Resolve the members of a mapped type { [P in K]: T } */ @@ -27883,8 +28075,7 @@ var ts; return getObjectFlags(type) & 32 /* Mapped */ && !!type.declaration.questionToken; } function isGenericMappedType(type) { - return getObjectFlags(type) & 32 /* Mapped */ && - maybeTypeOfKind(getConstraintTypeFromMappedType(type), 540672 /* TypeVariable */ | 262144 /* Index */); + return getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -27990,6 +28181,10 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + var transformed = getTransformedIndexedAccessType(type); + if (transformed) { + return transformed; + } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; @@ -28057,11 +28252,18 @@ var ts; return stringType; } if (t.flags & 524288 /* IndexedAccess */) { + var transformed = getTransformedIndexedAccessType(t); + if (transformed) { + return getBaseConstraint(transformed); + } var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; } + if (isGenericMappedType(t)) { + return emptyObjectType; + } return t; } } @@ -28608,6 +28810,9 @@ var ts; } return signature.resolvedReturnType; } + function isResolvingReturnTypeOfSignature(signature) { + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); @@ -28680,7 +28885,7 @@ var ts; function getIndexInfoOfSymbol(symbol, kind) { var declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64 /* Readonly */) !== 0, declaration); + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration); } return undefined; } @@ -28978,8 +29183,8 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; switch (declaration.kind) { case 229 /* ClassDeclaration */: case 230 /* InterfaceDeclaration */: @@ -29475,17 +29680,16 @@ var ts; return getTypeOfSymbol(prop); } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { + if (!(indexType.flags & 6144 /* Nullable */) && isTypeAssignableToKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); - return unknownType; } return indexInfo.type; } @@ -29517,35 +29721,84 @@ var ts; return anyType; } function getIndexedAccessForMappedType(type, indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - return unknownType; + if (accessNode) { + // Check if the index type is assignable to 'keyof T' for the object type. + if (!isTypeAssignableTo(indexType, getIndexType(type))) { + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(type)); + return unknownType; + } + if (accessNode.kind === 180 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && type.declaration.readonlyToken) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + } } var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); } + function isGenericObjectType(type) { + return type.flags & 540672 /* TypeVariable */ ? true : + getObjectFlags(type) & 32 /* Mapped */ ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : + type.flags & 196608 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericObjectType) : + false; + } + function isGenericIndexType(type) { + return type.flags & (540672 /* TypeVariable */ | 262144 /* Index */) ? true : + type.flags & 196608 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericIndexType) : + false; + } + // Return true if the given type is a non-generic object type with a string index signature and no + // other members. + function isStringIndexOnlyType(type) { + if (type.flags & 32768 /* Object */ && !isGenericMappedType(type)) { + var t = resolveStructuredTypeMembers(type); + return t.properties.length === 0 && + t.callSignatures.length === 0 && t.constructSignatures.length === 0 && + t.stringIndexInfo && !t.numberIndexInfo; + } + return false; + } + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. + function getTransformedIndexedAccessType(type) { + var objectType = type.objectType; + if (objectType.flags & 131072 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); + } + else { + regularTypes.push(t); + } + } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + return undefined; + } function getIndexedAccessType(objectType, indexType, accessNode) { - // If the index type is generic, if the object type is generic and doesn't originate in an expression, - // or if the object type is a mapped type with a generic constraint, we are performing a higher-order - // index access where we cannot meaningfully access the properties of the object type. Note that for a - // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to - // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved - // eagerly using the constraint type of 'this' at the given location. - if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || - maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) || - isGenericMappedType(objectType)) { + // If the object type is a mapped type { [P in K]: E }, where K is generic, we instantiate E using a mapper + // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we + // construct the type Box. + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + // Otherwise, if the index type is generic, or if the object type is generic and doesn't originate in an + // expression, we are performing a higher-order index access where we cannot meaningfully access the properties + // of the object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates + // in an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' + // has always been resolved eagerly using the constraint type of 'this' at the given location. + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { if (objectType.flags & 1 /* Any */) { return objectType; } - // If the object type is a mapped type { [P in K]: E }, we instantiate E using a mapper that substitutes - // the index type for P. For example, for an index access { [P in K]: Box }[X], we construct the - // type Box. - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } - // Otherwise we defer the operation by creating an indexed access type. + // Defer the operation by creating an indexed access type. var id = objectType.id + "," + indexType.id; var type = indexedAccessTypes.get(id); if (!type) { @@ -29759,7 +30012,7 @@ var ts; var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 230 /* InterfaceDeclaration */)) { - if (!(ts.getModifierFlags(container) & 32 /* Static */) && + if (!ts.hasModifier(container, 32 /* Static */) && (container.kind !== 152 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } @@ -29912,7 +30165,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.inferences) : + createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function identityMapper(type) { @@ -30222,16 +30475,16 @@ var ts; if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - // For arrow functions we now know we're not context sensitive. - if (node.kind === 187 /* ArrowFunction */) { - return false; + if (node.kind !== 187 /* ArrowFunction */) { + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. + var parameter = ts.firstOrUndefined(node.parameters); + if (!(parameter && ts.parameterIsThisKeyword(parameter))) { + return true; + } } - // If the first parameter is not an explicit 'this' parameter, then the function has - // an implicit 'this' parameter which is subject to contextual typing. Otherwise we - // know that all parameters (including 'this') have type annotations and nothing is - // subject to contextual typing. - var parameter = ts.firstOrUndefined(node.parameters); - return !(parameter && ts.parameterIsThisKeyword(parameter)); + // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. + return node.body.kind === 207 /* Block */ ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); @@ -30317,7 +30570,7 @@ var ts; return 0 /* False */; } if (source.typeParameters) { - source = instantiateSignatureInContextOf(source, target); + source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); @@ -30376,7 +30629,7 @@ var ts; // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions if (target.typePredicate) { if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(target.typePredicate)) { if (reportErrors) { @@ -30395,7 +30648,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -30404,11 +30657,13 @@ var ts; return 0 /* False */; } if (source.kind === 1 /* Identifier */) { - var sourceIdentifierPredicate = source; - var targetIdentifierPredicate = target; - if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + var sourcePredicate = source; + var targetPredicate = target; + var sourceIndex = sourcePredicate.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); + var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); + if (sourceIndex !== targetIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourcePredicate.parameterName, targetPredicate.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0 /* False */; @@ -30560,8 +30815,7 @@ var ts; return true; } if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); + var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1 /* Succeeded */; } @@ -30697,11 +30951,21 @@ var ts; !(target.flags & 65536 /* Union */) && !isIntersectionConstituent && source !== globalObjectType && - getPropertiesOfType(source).length > 0 && + (getPropertiesOfType(source).length > 0 || + getSignaturesOfType(source, 0 /* Call */).length > 0 || + getSignaturesOfType(source, 1 /* Construct */).length > 0) && isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { - reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + var calls = getSignaturesOfType(source, 0 /* Call */); + var constructs = getSignaturesOfType(source, 1 /* Construct */); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } } return 0 /* False */; } @@ -30929,7 +31193,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var id = getRelationKey(source, target, relation); var related = relation.get(id); if (related !== undefined) { if (reportErrors && related === 2 /* Failed */) { @@ -31411,6 +31675,11 @@ var ts; if (sourceInfo) { return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); } + if (isGenericMappedType(source)) { + // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } + // if T is related to U. + return kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + } if (isObjectLiteralType(source)) { var related = -1 /* True */; if (kind === 0 /* String */) { @@ -31444,8 +31713,8 @@ var ts; if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; - var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */); // A public, protected and private signature is assignable to a private signature. if (targetAccessibility === 8 /* Private */) { return true; @@ -31464,6 +31733,50 @@ var ts; return false; } } + function isUnconstrainedTypeParameter(type) { + return type.flags & 16384 /* TypeParameter */ && !getConstraintFromTypeParameter(type); + } + function isTypeReferenceWithGenericArguments(type) { + return getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, isUnconstrainedTypeParameter); + } + /** + * getTypeReferenceId(A) returns "111=0-12=1" + * where A.id=111 and number.id=12 + */ + function getTypeReferenceId(type, typeParameters) { + var result = "" + type.target.id; + for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { + var t = _a[_i]; + if (isUnconstrainedTypeParameter(t)) { + var index = ts.indexOf(typeParameters, t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + } + else { + result += "-" + t.id; + } + } + return result; + } + /** + * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. + * For other cases, the types ids are used. + */ + function getRelationKey(source, target, relation) { + if (relation === identityRelation && source.id > target.id) { + var temp = source; + source = target; + target = temp; + } + if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { + var typeParameters = []; + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + } + return source.id + "," + target.id; + } // 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) { @@ -31509,7 +31822,7 @@ var ts; var symbol = type.symbol; if (symbol && symbol.flags & 32 /* Class */) { var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.getModifierFlags(declaration) & 128 /* Abstract */) { + if (declaration && ts.hasModifier(declaration, 128 /* Abstract */)) { return true; } } @@ -31960,13 +32273,14 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(signature, flags, baseInferences) { + function createInferenceContext(signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); var context = mapper; context.mappedTypes = signature.typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; + context.compareTypes = compareTypes || compareTypesAssignable; return context; function mapper(t) { for (var i = 0; i < inferences.length; i++) { @@ -32061,6 +32375,19 @@ var ts; return inference.candidates && getUnionType(inference.candidates, /*subtypeReduction*/ true); } } + function isPossiblyAssignableTo(source, target) { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + if (!(targetProp.flags & (16777216 /* Optional */ | 4194304 /* Prototype */))) { + var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (!sourceProp) { + return false; + } + } + } + return true; + } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; @@ -32257,15 +32584,19 @@ var ts; return; } } - inferFromProperties(source, target); - inferFromSignatures(source, target, 0 /* Call */); - inferFromSignatures(source, target, 1 /* Construct */); - inferFromIndexTypes(source, target); + // Infer from the members of source and target only if the two types are possibly related. We check + // in both directions because we may be inferring for a co-variant or a contra-variant position. + if (isPossiblyAssignableTo(source, target) || isPossiblyAssignableTo(target, source)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { - var targetProp = properties_5[_i]; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -32382,7 +32713,7 @@ var ts; var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { inference.inferredType = inferredType = instantiatedConstraint; } } @@ -32440,16 +32771,6 @@ var ts; } return undefined; } - function getLeftmostIdentifierOrThis(node) { - switch (node.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - return node; - case 179 /* PropertyAccessExpression */: - return getLeftmostIdentifierOrThis(node.expression); - } - return undefined; - } function getBindingElementNameText(element) { if (element.parent.kind === 174 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; @@ -32975,7 +33296,7 @@ var ts; parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -33143,7 +33464,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { + if (isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -33978,7 +34299,7 @@ var ts; break; case 149 /* PropertyDeclaration */: case 148 /* PropertySignature */: - if (ts.getModifierFlags(container) & 32 /* Static */) { + if (ts.hasModifier(container, 32 /* Static */)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } @@ -34081,7 +34402,7 @@ var ts; if (!isCallExpression && container.kind === 152 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } - if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { + if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { nodeCheckFlag = 512 /* SuperStatic */; } else { @@ -34144,7 +34465,7 @@ var ts; // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment // while a property access can. - if (container.kind === 151 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { + if (container.kind === 151 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -34202,7 +34523,7 @@ var ts; // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression if (ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */) { - if (ts.getModifierFlags(container) & 32 /* Static */) { + if (ts.hasModifier(container, 32 /* Static */)) { return container.kind === 151 /* MethodDeclaration */ || container.kind === 150 /* MethodSignature */ || container.kind === 153 /* GetAccessor */ || @@ -34414,7 +34735,7 @@ var ts; // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature // and that call signature is non-generic, return statements are contextually typed by the return type of the signature var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); - if (signature) { + if (signature && !isResolvingReturnTypeOfSignature(signature)) { return getReturnTypeOfSignature(signature); } return undefined; @@ -34543,12 +34864,12 @@ var ts; } if (ts.isJsxAttribute(node.parent)) { // JSX expression is in JSX attribute - return getTypeOfPropertyOfType(attributesType, node.parent.name.escapedText); + return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); } else if (node.parent.kind === 249 /* JsxElement */) { // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; + return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; } else { // JSX expression is in JSX spread attribute @@ -34564,7 +34885,7 @@ var ts; if (!attributesType || isTypeAny(attributesType)) { return undefined; } - return getTypeOfPropertyOfType(attributesType, attribute.name.escapedText); + return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { return attributesType; @@ -34832,10 +35153,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), 84 /* NumberLike */); - } - function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || isTypeOfKind(type, kind); + return isTypeAssignableToKind(checkComputedPropertyName(name), 84 /* NumberLike */); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -34870,7 +35188,9 @@ 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, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { + if (links.resolvedType.flags & 6144 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */) && + !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -35484,9 +35804,7 @@ var ts; * emptyObjectType if there is no "prop" in the element instance type */ function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (!elementType) { - elementType = checkExpression(openingLikeElement.tagName); - } + if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } if (elementType.flags & 65536 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { @@ -35607,11 +35925,12 @@ var ts; */ function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { + var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; + if (!links[linkLocation]) { var elemClassType = getJsxGlobalElementClassType(); - return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); } - return links.resolvedJsxElementAttributesType; + return links[linkLocation]; } /** * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. @@ -35933,9 +36252,12 @@ var ts; } var prop = getPropertyOfType(apparentType, right.escapedText); if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */); - if (stringIndexType) { - return stringIndexType; + var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); + if (indexInfo && indexInfo.type) { + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + return indexInfo.type; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); @@ -36084,7 +36406,7 @@ var ts; if (prop && noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { + prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } @@ -36407,8 +36729,8 @@ var ts; return undefined; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) - function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature, 1 /* InferUnionTypes */); + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + var context = createInferenceContext(signature, 1 /* InferUnionTypes */, compareTypes); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); @@ -36780,7 +37102,7 @@ var ts; return getLiteralType(element.name.text); case 144 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { + if (isTypeAssignableToKind(nameType, 512 /* ESSymbol */)) { return nameType; } else { @@ -36921,9 +37243,10 @@ var ts; // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. + var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; var excludeArgument; var excludeCount = 0; - if (!isDecorator) { + if (!isDecorator && !isSingleNonGenericCandidate) { // We do not need to call `getEffectiveArgumentCount` here as it only // applies when calculating the number of arguments for a decorator. for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { @@ -37068,6 +37391,17 @@ var ts; if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; candidateForTypeArgumentError = undefined; + if (isSingleNonGenericCandidate) { + var candidate = candidates[0]; + if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + return undefined; + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = candidate; + return undefined; + } + return candidate; + } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { @@ -37230,7 +37564,7 @@ var ts; // In the case of a merged class-module or class-interface declaration, // 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 */) { + if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } @@ -37277,9 +37611,9 @@ var ts; return true; } var declaration = signature.declaration; - var modifiers = ts.getModifierFlags(declaration); + var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); // Public constructor is accessible. - if (!(modifiers & 24 /* NonPublicAccessibilityModifier */)) { + if (!modifiers) { return true; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -37488,7 +37822,7 @@ var ts; */ function checkCallExpression(node) { // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); + checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 97 /* SuperKeyword */) { return voidType; @@ -37528,7 +37862,7 @@ var ts; } function checkImportCallExpression(node) { // Check grammar of dynamic import - checkGrammarArguments(node, node.arguments) || checkGrammarImportCallExpression(node); + checkGrammarArguments(node.arguments) || checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } @@ -37546,11 +37880,33 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeOfSymbol(esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); } } return createPromiseReturnType(node, anyType); } + function getTypeWithSyntheticDefaultImportType(type, symbol) { + if (allowSyntheticDefaultImports && type && type !== unknownType) { + var synthType = type; + if (!synthType.syntheticType) { + if (!getPropertyOfType(type, "default" /* Default */)) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + anonymousSymbol.type = defaultContainingObject; + synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + } + else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } function isCommonJsRequire(node) { if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { return false; @@ -37675,15 +38031,15 @@ var ts; } // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push // the destructured type into the contained binding elements. - function assignBindingElementTypes(node) { - if (ts.isBindingPattern(node.name)) { - for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71 /* Identifier */) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); - } - assignBindingElementTypes(element); + function assignBindingElementTypes(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 71 /* Identifier */) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + else { + assignBindingElementTypes(element.name); } } } @@ -37692,13 +38048,14 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = contextualType; - 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 && - (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(name); + var decl = parameter.valueDeclaration; + if (decl.name.kind !== 71 /* Identifier */) { + // if inference didn't come up with anything but {}, fall back to the binding pattern if present. + if (links.type === emptyObjectType) { + links.type = getTypeFromBindingPattern(decl.name); + } + assignBindingElementTypes(decl.name); } - assignBindingElementTypes(parameter.valueDeclaration); } } function createPromiseType(promisedType) { @@ -37934,16 +38291,16 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - // Grammar checking - var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186 /* FunctionExpression */) { - checkGrammarForGenerator(node); - } // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { checkNodeDeferred(node); return anyFunctionType; } + // Grammar checking + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 186 /* FunctionExpression */) { + checkGrammarForGenerator(node); + } var links = getNodeLinks(node); var type = getTypeOfSymbol(node.symbol); // Check if function expression is contextually typed and assign parameter types if so. @@ -38028,7 +38385,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { + if (!isTypeAssignableToKind(type, 84 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -38129,8 +38486,13 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + if (node.operand.kind === 8 /* NumericLiteral */) { + if (node.operator === 38 /* MinusToken */) { + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + } + else if (node.operator === 37 /* PlusToken */) { + return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); + } } switch (node.operator) { case 37 /* PlusToken */: @@ -38186,33 +38548,22 @@ var ts; } return false; } - // Return true if type is of the given kind. A union type is of a given kind if all constituent types - // are of the given kind. An intersection type is of a given kind if at least one constituent type is - // of the given kind. - function isTypeOfKind(type, kind) { - if (type.flags & kind) { + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { return true; } - if (type.flags & 65536 /* Union */) { - var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; - if (!isTypeOfKind(t, kind)) { - return false; - } - } - return true; + if (strict && source.flags & (1 /* Any */ | 1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */)) { + return false; } - if (type.flags & 131072 /* Intersection */) { - var types = type.types; - for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { - var t = types_19[_a]; - if (isTypeOfKind(t, kind)) { - return true; - } - } - } - return false; + return (kind & 84 /* NumberLike */ && isTypeAssignableTo(source, numberType)) || + (kind & 262178 /* StringLike */ && isTypeAssignableTo(source, stringType)) || + (kind & 136 /* BooleanLike */ && isTypeAssignableTo(source, booleanType)) || + (kind & 1024 /* Void */ && isTypeAssignableTo(source, voidType)) || + (kind & 8192 /* Never */ && isTypeAssignableTo(source, neverType)) || + (kind & 4096 /* Null */ && isTypeAssignableTo(source, nullType)) || + (kind & 2048 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || + (kind & 512 /* ESSymbol */ && isTypeAssignableTo(source, esSymbolType)) || + (kind & 16777216 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); } function isConstEnumObjectType(type) { return getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); @@ -38229,7 +38580,7 @@ var ts; // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. // The result is always of the Boolean primitive type. // NOTE: do not raise error if leftType is unknown as related error was already reported - if (isTypeOfKind(leftType, 8190 /* Primitive */)) { + if (!isTypeAny(leftType) && isTypeAssignableToKind(leftType, 8190 /* Primitive */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported @@ -38251,18 +38602,18 @@ 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, 84 /* NumberLike */ | 512 /* ESSymbol */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(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 */)) { + if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 540672 /* TypeVariable */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var p = properties_6[_i]; + for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { + var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); } return sourceType; @@ -38541,30 +38892,28 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeOfKind(leftType, 1 /* Any */ | 262178 /* StringLike */) && !isTypeOfKind(rightType, 1 /* Any */ | 262178 /* StringLike */)) { + if (!isTypeAssignableToKind(leftType, 262178 /* StringLike */) && !isTypeAssignableToKind(rightType, 262178 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeOfKind(leftType, 84 /* NumberLike */) && isTypeOfKind(rightType, 84 /* NumberLike */)) { + if (isTypeAssignableToKind(leftType, 84 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 84 /* NumberLike */, /*strict*/ true)) { // 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; } - else { - if (isTypeOfKind(leftType, 262178 /* StringLike */) || isTypeOfKind(rightType, 262178 /* StringLike */)) { - // If one or both operands are of the String primitive type, the result is of the String primitive type. - resultType = stringType; - } - else if (isTypeAny(leftType) || isTypeAny(rightType)) { - // Otherwise, the result is of type Any. - // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. - resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; - } - // Symbols are not allowed at all in arithmetic expressions - if (resultType && !checkForDisallowedESSymbolOperand(operator)) { - return resultType; - } + else if (isTypeAssignableToKind(leftType, 262178 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 262178 /* StringLike */, /*strict*/ true)) { + // If one or both operands are of the String primitive type, the result is of the String primitive type. + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + // Otherwise, the result is of type Any. + // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; + } + // Symbols are not allowed at all in arithmetic expressions + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; } if (!resultType) { reportOperatorError(); @@ -38749,13 +39098,12 @@ var ts; return getBestChoiceType(type1, type2); } function checkLiteralExpression(node) { - if (node.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(node); - } switch (node.kind) { + case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101 /* TrueKeyword */: return trueType; @@ -38951,6 +39299,7 @@ var ts; return checkSuperExpression(node); case 95 /* NullKeyword */: return nullWideningType; + case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: case 101 /* TrueKeyword */: @@ -38958,8 +39307,6 @@ var ts; return checkLiteralExpression(node); case 196 /* TemplateExpression */: return checkTemplateExpression(node); - case 13 /* NoSubstitutionTemplateLiteral */: - return stringType; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 177 /* ArrayLiteralExpression */: @@ -39058,7 +39405,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.getModifierFlags(node) & 92 /* ParameterPropertyModifier */) { + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { func = ts.getContainingFunction(node); if (!(func.kind === 152 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -39264,7 +39611,7 @@ var ts; } } else { - var isStatic = ts.getModifierFlags(member) & 32 /* Static */; + var isStatic = ts.hasModifier(member, 32 /* Static */); var names = isStatic ? staticNames : instanceNames; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { @@ -39320,7 +39667,7 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; var memberNameNode = member.name; - var isStatic = ts.getModifierFlags(member) & 32 /* Static */; + var isStatic = ts.hasModifier(member, 32 /* Static */); if (isStatic && memberNameNode) { var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); switch (memberName) { @@ -39418,7 +39765,7 @@ var ts; checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.getModifierFlags(node) & 128 /* Abstract */ && node.body) { + if (ts.hasModifier(node, 128 /* Abstract */) && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -39458,17 +39805,9 @@ var ts; } return ts.forEachChild(n, containsSuperCall); } - function markThisReferencesAsErrors(n) { - if (n.kind === 99 /* ThisKeyword */) { - error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - } - else if (n.kind !== 186 /* FunctionExpression */ && n.kind !== 228 /* FunctionDeclaration */) { - ts.forEachChild(n, markThisReferencesAsErrors); - } - } function isInstancePropertyWithInitializer(n) { return n.kind === 149 /* PropertyDeclaration */ && - !(ts.getModifierFlags(n) & 32 /* Static */) && + !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } // TS 1.0 spec (April 2014): 8.3.2 @@ -39488,8 +39827,8 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92 /* ParameterPropertyModifier */; }); + var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -39540,10 +39879,12 @@ var ts; var otherKind = node.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if ((ts.getModifierFlags(node) & 28 /* AccessibilityModifier */) !== (ts.getModifierFlags(otherAccessor) & 28 /* AccessibilityModifier */)) { + var nodeFlags = ts.getModifierFlags(node); + var otherFlags = ts.getModifierFlags(otherAccessor); + if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if (ts.hasModifier(node, 128 /* Abstract */) !== ts.hasModifier(otherAccessor, 128 /* Abstract */)) { + if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } // TypeScript 1.0 spec (April 2014): 4.5 @@ -39591,7 +39932,7 @@ var ts; function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); if (node.kind === 159 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { - grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); if (type !== unknownType) { @@ -39600,7 +39941,17 @@ var ts; ts.forEach(node.typeArguments, checkSourceElement); if (produceDiagnostics) { var symbol = getNodeLinks(node).resolvedSymbol; - var typeParameters = symbol.flags & 524288 /* TypeAlias */ ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; + if (!symbol) { + // There is no resolved symbol cached if the type resolved to a builtin + // via JSDoc type reference resolution (eg, Boolean became boolean), none + // of which are generic when they have no associated symbol + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return; + } + var typeParameters = symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters; + if (!typeParameters && getObjectFlags(type) & 4 /* Reference */) { + typeParameters = type.target.localTypeParameters; + } checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } @@ -39645,18 +39996,17 @@ var ts; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { return type; } - // 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, 84 /* NumberLike */)) { - var constraint = getBaseConstraintOfType(objectType); - if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { - return type; - } + // Check if we're indexing with a numeric type and if either object or index types + // is a generic type with a constraint that has a numeric index signature. + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { + return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); return type; } function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } function checkMappedType(node) { @@ -39667,7 +40017,7 @@ var ts; checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); } function isPrivateWithinAmbient(node) { - return (ts.getModifierFlags(node) & 8 /* Private */) && ts.isInAmbientContext(node); + return ts.hasModifier(node, 8 /* Private */) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); @@ -39767,13 +40117,13 @@ var ts; (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { var reportError = (node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */) && - (ts.getModifierFlags(node) & 32 /* Static */) !== (ts.getModifierFlags(subsequentNode) & 32 /* Static */); + ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members // 2. something with the same name was defined before the set of overloads that prevents them from merging // here we'll report error only for the first case since for second we should already report error in binder if (reportError) { - var diagnostic = ts.getModifierFlags(node) & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -39791,7 +40141,7 @@ var ts; else { // Report different errors regarding non-consecutive blocks of declarations depending on whether // the node in question is abstract. - if (ts.getModifierFlags(node) & 128 /* Abstract */) { + if (ts.hasModifier(node, 128 /* Abstract */)) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -39801,8 +40151,8 @@ var ts; } var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var current = declarations_5[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); var inAmbientContextOrInterface = node.parent.kind === 230 /* InterfaceDeclaration */ || node.parent.kind === 163 /* TypeLiteral */ || inAmbientContext; @@ -39859,7 +40209,7 @@ var ts; } // Abstract methods can't have an implementation -- in particular, they don't need one. if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -40426,7 +40776,7 @@ var ts; // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. var firstDeclaration = ts.find(localSymbol.declarations, // Get first non javascript function declaration - function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)); }); + function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536 /* JavaScriptFile */); }); // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); @@ -40569,14 +40919,14 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 151 /* MethodDeclaration */ || member.kind === 149 /* PropertyDeclaration */) { - if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8 /* Private */) { + if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); } } else if (member.kind === 152 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8 /* Private */) { + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); } } @@ -40997,7 +41347,7 @@ var ts; 128 /* Abstract */ | 64 /* Readonly */ | 32 /* Static */; - return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); + return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); @@ -41162,7 +41512,7 @@ var ts; } // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { + if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 540672 /* TypeVariable */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -41662,7 +42012,7 @@ var ts; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!(ts.getModifierFlags(member) & 32 /* Static */) && ts.hasDynamicName(member)) { + if (!ts.hasModifier(member, 32 /* Static */) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); @@ -41773,8 +42123,8 @@ var ts; if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { // Report an error on every conflicting declaration. var name = symbolToString(symbol); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } @@ -41783,8 +42133,8 @@ var ts; function areTypeParametersIdentical(declarations, typeParameters) { var maxTypeArgumentCount = ts.length(typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; // If this declaration has too few or too many type parameters, we report an error var numTypeParameters = ts.length(declaration.typeParameters); if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { @@ -41827,7 +42177,7 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (!node.name && !(ts.getModifierFlags(node) & 512 /* Default */)) { + if (!node.name && !ts.hasModifier(node, 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -41925,7 +42275,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { var declaration = signatures[0].declaration; - if (declaration && ts.getModifierFlags(declaration) & 8 /* Private */) { + if (declaration && ts.hasModifier(declaration, 8 /* Private */)) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); @@ -41981,7 +42331,7 @@ var ts; // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. - if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128 /* Abstract */))) { + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { if (derivedClassDecl.kind === 199 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -42032,8 +42382,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { - var prop = properties_7[_a]; + for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { + var prop = properties_8[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -42307,8 +42657,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; if ((declaration.kind === 229 /* ClassDeclaration */ || (declaration.kind === 228 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { @@ -42558,7 +42908,7 @@ var ts; // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -42586,7 +42936,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (ts.getModifierFlags(node) & 1 /* Export */) { + if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -42617,7 +42967,7 @@ var ts; // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -42682,7 +43032,7 @@ var ts; return; } // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 71 /* Identifier */) { @@ -42736,8 +43086,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -43046,7 +43396,7 @@ var ts; return []; } var symbols = ts.createSymbolTable(); - var memberFlags = 0 /* None */; + var isStatic = false; populateSymbols(); return symbolsToArray(symbols); function populateSymbols() { @@ -43075,7 +43425,7 @@ var ts; // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. - if (!(memberFlags & 32 /* Static */)) { + if (!isStatic) { copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); } break; @@ -43089,7 +43439,7 @@ var ts; if (ts.introducesArgumentsExoticObject(location)) { copySymbol(argumentsSymbol, meaning); } - memberFlags = ts.getModifierFlags(location); + isStatic = ts.hasModifier(location, 32 /* Static */); location = location.parent; } copySymbols(globals, meaning); @@ -43351,12 +43701,7 @@ var ts; // index access if (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { var objectType = getTypeOfExpression(node.parent.expression); - if (objectType === unknownType) - return undefined; - var apparentType = getApparentType(objectType); - if (apparentType === unknownType) - return undefined; - return getPropertyOfType(apparentType, node.text); + return getPropertyOfType(objectType, node.text); } break; } @@ -43487,7 +43832,7 @@ var ts; */ function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return ts.getModifierFlags(node) & 32 /* Static */ + return ts.hasModifier(node, 32 /* Static */) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -43769,13 +44114,13 @@ var ts; return strictNullChecks && !isOptionalParameter(parameter) && parameter.initializer && - !(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - !!(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function getNodeCheckFlags(node) { return getNodeLinks(node).flags; @@ -43835,22 +44180,22 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { + else if (isTypeAssignableToKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeOfKind(type, 136 /* BooleanLike */)) { + else if (isTypeAssignableToKind(type, 136 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 84 /* NumberLike */)) { + else if (isTypeAssignableToKind(type, 84 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 262178 /* StringLike */)) { + else if (isTypeAssignableToKind(type, 262178 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 512 /* ESSymbol */)) { + else if (isTypeAssignableToKind(type, 512 /* ESSymbol */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -44346,7 +44691,7 @@ var ts; node.kind !== 154 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 229 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { + if (!(node.parent.kind === 229 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -44469,8 +44814,7 @@ var ts; if (list && list.hasTrailingComma) { var start = list.end - ",".length; var end = list.end; - var sourceFile = ts.getSourceFileOfNode(list[0]); - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + return grammarErrorAtPos(list[0], start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); } } function checkGrammarTypeParameterList(typeParameters, file) { @@ -44547,7 +44891,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (ts.getModifierFlags(parameter) !== 0) { + if (ts.hasModifiers(parameter)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -44582,19 +44926,18 @@ var ts; return checkGrammarForDisallowedTrailingComma(typeArguments) || checkGrammarForAtLeastOneTypeArgument(node, typeArguments); } - function checkGrammarForOmittedArgument(node, args) { + function checkGrammarForOmittedArgument(args) { if (args) { - var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; if (arg.kind === 200 /* OmittedExpression */) { - return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } } } - function checkGrammarArguments(node, args) { - return checkGrammarForOmittedArgument(node, args); + function checkGrammarArguments(args) { + return checkGrammarForOmittedArgument(args); } function checkGrammarHeritageClause(node) { var types = node.types; @@ -44603,8 +44946,7 @@ var ts; } if (types && types.length === 0) { var listType = ts.tokenToString(node.token); - var sourceFile = ts.getSourceFileOfNode(node); - return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } return ts.forEach(types, checkGrammarExpressionWithTypeArguments); } @@ -44850,10 +45192,10 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128 /* Abstract */)) { - return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } - else if (accessor.body && ts.getModifierFlags(accessor) & 128 /* Abstract */) { + else if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) { return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); } else if (accessor.typeParameters) { @@ -44910,7 +45252,7 @@ var ts; return true; } else if (node.body === undefined) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } if (ts.isClassLike(node.parent)) { @@ -44991,7 +45333,7 @@ var ts; } if (node.initializer) { // Error on equals token which immediately precedes the initializer - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } } } @@ -45012,13 +45354,13 @@ var ts; else { // Error on equals token which immediate precedes the initializer var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { // Error on equals token which immediate precedes the initializer var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } else if (!node.initializer) { @@ -45081,7 +45423,7 @@ var ts; return true; } if (!declarationList.declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } } function allowLetAndConstDeclarations(parent) { @@ -45127,7 +45469,8 @@ var ts; return true; } } - function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { + function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); if (!hasParseDiagnostics(sourceFile)) { diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; @@ -45142,7 +45485,7 @@ var ts; } function checkGrammarConstructorTypeParameters(node) { if (node.typeParameters) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + return grammarErrorAtPos(node, node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -45196,7 +45539,7 @@ var ts; node.kind === 244 /* ExportDeclaration */ || node.kind === 243 /* ExportAssignment */ || node.kind === 236 /* NamespaceExportDeclaration */ || - ts.getModifierFlags(node) & (2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { + ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -48142,7 +48485,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_8 = []; + var properties_9 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -48152,7 +48495,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_8.push(getter); + properties_9.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -48163,15 +48506,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_8.push(setter); + properties_9.push(setter); } - properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_8, multiLine) + ts.createObjectLiteral(properties_9, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -50628,11 +50971,14 @@ var ts; : numElements, location), /*reuseIdentifierExpressions*/ false, location); } - else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)) { + else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0) + || ts.every(elements, ts.isOmittedExpression)) { // For anything other than a single-element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. Additionally, if we have zero elements // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, // so in that case, we'll intentionally create that temporary. + // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]", + // then we will create temporary variable. var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); } @@ -50919,7 +51265,16 @@ var ts; if (ts.hasModifier(node, 2 /* Ambient */)) { break; } - recordEmittedDeclarationInScope(node); + // Record these declarations provided that they have a name. + if (node.name) { + recordEmittedDeclarationInScope(node); + } + else { + // These nodes should always have names unless they are default-exports; + // however, class declaration parsing allows for undefined names, so syntactically invalid + // programs may also have an undefined name. + ts.Debug.assert(node.kind === 229 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + } break; } } @@ -51748,8 +52103,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addInitializedPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { - var property = properties_9[_i]; + for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { + var property = properties_10[_i]; var statement = ts.createStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); @@ -51764,8 +52119,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { - var property = properties_10[_i]; + for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { + var property = properties_11[_i]; var expression = transformInitializedProperty(property, receiver); expression.startsOnNewLine = true; ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); @@ -52928,33 +53283,30 @@ var ts; /** * Records that a declaration was emitted in the current scope, if it was the first * declaration for the provided symbol. - * - * NOTE: if there is ever a transformation above this one, we may not be able to rely - * on symbol names. */ function recordEmittedDeclarationInScope(node) { - var name = node.symbol && node.symbol.escapedName; - if (name) { - if (!currentScopeFirstDeclarationsOfName) { - currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); - } - if (!currentScopeFirstDeclarationsOfName.has(name)) { - currentScopeFirstDeclarationsOfName.set(name, node); - } + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); + } + var name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); } } /** - * Determines whether a declaration is the first declaration with the same name emitted - * in the current scope. + * Determines whether a declaration is the first declaration with + * the same name emitted in the current scope. */ function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name = node.symbol && node.symbol.escapedName; - if (name) { - return currentScopeFirstDeclarationsOfName.get(name) === node; - } + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; } - return false; + return true; + } + function declaredNameInScope(node) { + ts.Debug.assertNode(node.name, ts.isIdentifier); + return node.name.escapedText; } /** * Adds a leading VariableStatement for a enum or module declaration. @@ -53021,7 +53373,7 @@ var ts; if (!shouldEmitModuleDeclaration(node)) { return ts.createNotEmittedStatement(node); } - ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); + ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); enableSubstitutionForNamespaceExports(); var statements = []; // We request to be advised when the printer is about to print this node. This allows @@ -54050,6 +54402,8 @@ var ts; return visitExpressionStatement(node); case 185 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); + case 260 /* CatchClause */: + return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); } @@ -54130,6 +54484,12 @@ var ts; function visitParenthesizedExpression(node, noDestructuringValue) { return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } /** * Visits a BinaryExpression that contains a destructuring assignment. * @@ -54674,7 +55034,7 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -55378,7 +55738,7 @@ var ts; function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && ts.isStatement(node)) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 207 /* Block */))) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) || isTypeScriptClassWrapper(node); } @@ -55733,10 +56093,12 @@ var ts; var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); ts.setEmitFlags(outer, 1536 /* NoComments */); - return ts.createParen(ts.createCall(outer, + var result = ts.createParen(ts.createCall(outer, /*typeArguments*/ undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); + ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class "); + return result; } /** * Transforms a ClassExpression or ClassDeclaration into a function body. @@ -56654,13 +57016,14 @@ var ts; ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); if (node.transformFlags & 8388608 /* ContainsBindingPattern */ - && (ts.isBindingPattern(node.declarations[0].name) - || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. var firstDeclaration = ts.firstOrUndefined(declarations); - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + if (firstDeclaration) { + var lastDeclaration = ts.lastOrUndefined(declarations); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } } return declarationList; } @@ -57405,6 +57768,7 @@ var ts; function visitCatchClause(node) { var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); var updated; + ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); if (ts.isBindingPattern(node.variableDeclaration.name)) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); var newVariableDeclaration = ts.createVariableDeclaration(temp); @@ -59593,8 +59957,13 @@ var ts; } function transformAndEmitContinueStatement(node) { var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); - ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); - emitBreak(label, /*location*/ node); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid continue without a containing loop. Leave the node as is, per #17875. + emitStatement(node); + } } function visitContinueStatement(node) { if (inStatementContainingYield) { @@ -59607,8 +59976,13 @@ var ts; } function transformAndEmitBreakStatement(node) { var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); - ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); - emitBreak(label, /*location*/ node); + if (label > 0) { + emitBreak(label, /*location*/ node); + } + else { + // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875. + emitStatement(node); + } } function visitBreakStatement(node) { if (inStatementContainingYield) { @@ -59979,9 +60353,6 @@ var ts; var block = endBlock(); markLabel(block.endLabel); } - function isWithBlock(block) { - return block.kind === 1 /* With */; - } /** * Begins a code block for a generated `try` statement. */ @@ -60065,9 +60436,6 @@ var ts; emitNop(); exception.state = 3 /* Done */; } - function isExceptionBlock(block) { - return block.kind === 0 /* Exception */; - } /** * Begins a code block that supports `break` or `continue` statements that are defined in * the source tree and not from generated code. @@ -60218,23 +60586,24 @@ var ts; * @param labelText An optional name of a containing labeled statement. */ function findBreakTarget(labelText) { - ts.Debug.assert(blocks !== undefined); - if (labelText) { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { - return block.breakLabel; - } - else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { - return block.breakLabel; + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } } } - } - else { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledBreak(block)) { - return block.breakLabel; + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } } } } @@ -60246,20 +60615,21 @@ var ts; * @param labelText An optional name of a containing labeled statement. */ function findContinueTarget(labelText) { - ts.Debug.assert(blocks !== undefined); - if (labelText) { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { - return block.continueLabel; + if (blockStack) { + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } } } - } - else { - for (var i = blockStack.length - 1; i >= 0; i--) { - var block = blockStack[i]; - if (supportsUnlabeledContinue(block)) { - return block.continueLabel; + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } } } } @@ -60301,7 +60671,7 @@ var ts; * @param location An optional source map location for the statement. */ function createInlineBreak(label, location) { - ts.Debug.assert(label > 0, "Invalid label: " + label); + ts.Debug.assertLessThan(0, label, "Invalid label"); return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ createInstruction(3 /* Break */), createLabel(label) @@ -60642,31 +61012,33 @@ var ts; for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { var block = blocks[blockIndex]; var blockAction = blockActions[blockIndex]; - if (isExceptionBlock(block)) { - if (blockAction === 0 /* Open */) { - if (!exceptionBlockStack) { - exceptionBlockStack = []; + switch (block.kind) { + case 0 /* Exception */: + if (blockAction === 0 /* Open */) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; } - if (!statements) { - statements = []; + else if (blockAction === 1 /* Close */) { + currentExceptionBlock = exceptionBlockStack.pop(); } - exceptionBlockStack.push(currentExceptionBlock); - currentExceptionBlock = block; - } - else if (blockAction === 1 /* Close */) { - currentExceptionBlock = exceptionBlockStack.pop(); - } - } - else if (isWithBlock(block)) { - if (blockAction === 0 /* Open */) { - if (!withBlockStack) { - withBlockStack = []; + break; + case 1 /* With */: + if (blockAction === 0 /* Open */) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); } - withBlockStack.push(block); - } - else if (blockAction === 1 /* Close */) { - withBlockStack.pop(); - } + else if (blockAction === 1 /* Close */) { + withBlockStack.pop(); + } + break; } } } @@ -64580,14 +64952,14 @@ var ts; writer.writeLine(); } } - function emitTrailingCommentsOfPosition(pos) { + function emitTrailingCommentsOfPosition(pos, prefixSpace) { if (disabled) { return; } if (extendedDiagnostics) { ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); } - forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition); if (extendedDiagnostics) { ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); } @@ -64676,17 +65048,7 @@ var ts; * @return true if the comment is a triple-slash comment else false */ function isTripleSlashComment(commentPos, commentEnd) { - // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text - // so that we don't end up computing comment string and doing match for all // comments - if (currentText.charCodeAt(commentPos + 1) === 47 /* slash */ && - commentPos + 2 < commentEnd && - currentText.charCodeAt(commentPos + 2) === 47 /* slash */) { - var textSubStr = currentText.substring(commentPos, commentEnd); - return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || - textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? - true : false; - } - return false; + return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); } } ts.createCommentWriter = createCommentWriter; @@ -64972,7 +65334,6 @@ var ts; errorNameNode = declaration.name; var format = 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */ | - 2048 /* UseTypeAliasValue */ | (shouldUseResolverType ? 8192 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; @@ -64987,7 +65348,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 2048 /* UseTypeAliasValue */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); errorNameNode = undefined; } } @@ -65225,7 +65586,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 2048 /* UseTypeAliasValue */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); write(";"); writeLine(); return tempVarName; @@ -65898,6 +66259,10 @@ var ts; return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); } function writeVariableStatement(node) { + // If binding pattern doesn't have name, then there is nothing to be emitted for declaration file i.e. const [,] = [1,2]. + if (ts.every(node.declarationList && node.declarationList.declarations, function (decl) { return decl.name && ts.isEmptyBindingPattern(decl.name); })) { + return; + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.isLet(node.declarationList)) { @@ -67437,7 +67802,9 @@ var ts; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = { kind: 23 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; + var dotToken = ts.createToken(23 /* DotToken */); + dotToken.pos = dotRangeStart; + dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } @@ -67566,7 +67933,9 @@ var ts; var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + emitLeadingCommentsOfPosition(node.operatorToken.pos); writeTokenNode(node.operatorToken); + emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -67760,8 +68129,19 @@ var ts; emitWithPrefix(" ", node.label); write(";"); } + function emitTokenWithComment(token, pos, contextNode) { + var node = contextNode && ts.getParseTreeNode(contextNode); + if (node && node.kind === contextNode.kind) { + pos = ts.skipTrivia(currentSourceFile.text, pos); + } + pos = writeToken(token, pos, /*contextNode*/ contextNode); + if (node && node.kind === contextNode.kind) { + emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); + } + return pos; + } function emitReturnStatement(node) { - writeToken(96 /* ReturnKeyword */, node.pos, /*contextNode*/ node); + emitTokenWithComment(96 /* ReturnKeyword */, node.pos, /*contextNode*/ node); emitExpressionWithPrefix(" ", node.expression); write(";"); } @@ -68237,10 +68617,12 @@ var ts; function emitCatchClause(node) { var openParenPos = writeToken(74 /* CatchKeyword */, node.pos); write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); - emit(node.variableDeclaration); - writeToken(20 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); - write(" "); + if (node.variableDeclaration) { + writeToken(19 /* OpenParenToken */, openParenPos); + emit(node.variableDeclaration); + writeToken(20 /* CloseParenToken */, node.variableDeclaration.end); + write(" "); + } emit(node.block); } // @@ -69520,6 +69902,14 @@ var ts; var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } + // Map from a stringified PackageId to the source file with that id. + // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). + // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around. + var packageIdToSourceFile = ts.createMap(); + // Maps from a SourceFile's `.path` to the name of the package it was imported with. + var sourceFileToPackageName = ts.createMap(); + // See `sourceFileIsRedirectedTo`. + var redirectTargetsSet = ts.createMap(); var filesByName = ts.createMap(); // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing @@ -69588,6 +69978,8 @@ var ts; isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsSet: redirectTargetsSet, }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -69780,17 +70172,57 @@ var ts; var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2 /* Completely */; - for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { - var oldSourceFile = _a[_i]; + var oldSourceFiles = oldProgram.getSourceFiles(); + var SeenPackageName; + (function (SeenPackageName) { + SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; + SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; + })(SeenPackageName || (SeenPackageName = {})); + var seenPackageNames = ts.createMap(); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) : host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; } + ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + var fileChanged = void 0; + if (oldSourceFile.redirectInfo) { + // We got `newSourceFile` by path, so it is actually for the unredirected file. + // This lets us know if the unredirected file has changed. If it has we should break the redirect. + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + // Underlying file has changed. Might not redirect anymore. Must rebuild program. + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + newSourceFile = oldSourceFile; // Use the redirect. + } + else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + // If a redirected-to source file changes, the redirect may be broken. + if (newSourceFile !== oldSourceFile) { + return oldProgram.structureIsReused = 0 /* Not */; + } + fileChanged = false; + } + else { + fileChanged = newSourceFile !== oldSourceFile; + } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); - if (oldSourceFile !== newSourceFile) { + var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== undefined) { + // If there are 2 different source files for the same package name and at least one of them changes, + // they might become redirects. So we must rebuild the program. + var prevKind = seenPackageNames.get(packageName); + var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */; + if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) { + return oldProgram.structureIsReused = 0 /* Not */; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { // The `newSourceFile` object was created for the new program. if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed @@ -69831,8 +70263,8 @@ var ts; } 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; + for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { + var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); @@ -69875,8 +70307,8 @@ var ts; if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { return oldProgram.structureIsReused = 1 /* SafeModules */; } - for (var _d = 0, _e = oldProgram.getMissingFilePaths(); _d < _e.length; _d++) { - var p = _e[_d]; + for (var _c = 0, _d = oldProgram.getMissingFilePaths(); _c < _d.length; _c++) { + var p = _d[_c]; filesByName.set(p, undefined); } // update fileName -> file mapping @@ -69885,11 +70317,13 @@ var ts; } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _f = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _f < modifiedSourceFiles_2.length; _f++) { - var modifiedFile = modifiedSourceFiles_2[_f]; + for (var _e = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _e < modifiedSourceFiles_2.length; _e++) { + var modifiedFile = modifiedSourceFiles_2[_e]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsSet = oldProgram.redirectTargetsSet; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { @@ -70436,7 +70870,7 @@ var ts; } /** This has side effects through `findSourceFile`. */ function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, /*packageId*/ undefined); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -70453,8 +70887,25 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + var redirect = Object.create(redirectTarget); + redirect.fileName = fileName; + redirect.path = path; + redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + Object.defineProperties(redirect, { + id: { + get: function () { return this.redirectInfo.redirectTarget.id; }, + set: function (value) { this.redirectInfo.redirectTarget.id = value; }, + }, + symbol: { + get: function () { return this.redirectInfo.redirectTarget.symbol; }, + set: function (value) { this.redirectInfo.redirectTarget.symbol = value; }, + }, + }); + return redirect; + } // Get source file from normalized fileName - function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) { if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -70490,6 +70941,25 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + if (packageId) { + var packageIdKey = packageId.name + "@" + packageId.version; + var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + // Some other SourceFile already exists with this package name and version. + // Instead of creating a duplicate, just redirect to the existing one. + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); + redirectTargetsSet.set(fileFromPackageId.path, true); + filesByName.set(path, dupFile); + sourceFileToPackageName.set(path, packageId.name); + files.push(dupFile); + return dupFile; + } + else if (file) { + // This is the first source file to have this packageId. + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageId.name); + } + } filesByName.set(path, file); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); @@ -70630,7 +71100,7 @@ var ts; else if (shouldAddFile) { var path = toPath(resolvedFileName); var pos = ts.skipTrivia(file.text, file.imports[i].pos); - findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, file, pos, file.imports[i].end); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -70785,8 +71255,8 @@ var ts; } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted - if (options.outDir || - options.sourceRoot || + if (options.outDir || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { // Precalculate and cache the common source directory var dir = getCommonSourceDirectory(); @@ -71349,6 +71819,12 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, // Source Maps { name: "sourceRoot", @@ -72006,7 +72482,7 @@ var ts; if (option && typeof option.type !== "string") { var customOption = option; // Validate custom option type - if (!customOption.type.has(text)) { + if (!customOption.type.has(text.toLowerCase())) { errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); } } @@ -72306,13 +72782,10 @@ var ts; } } else { - // If no includes were specified, exclude common package folders and the outDir - var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - specs.push(outDir); + excludeSpecs = [outDir]; } - excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; @@ -72573,7 +73046,7 @@ var ts; return value; } else if (typeof option.type !== "string") { - return option.type.get(value); + return option.type.get(typeof value === "string" ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -72748,23 +73221,13 @@ var ts; }; } function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { - var validSpecs = []; - for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { - var spec = specs_1[_i]; - if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); } - else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); - } - else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); - } - else { - validSpecs.push(spec); - } - } - return validSpecs; + return diag === undefined; + }); function createDiagnostic(message, spec) { if (jsonSourceFile && jsonSourceFile.jsonObject) { for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { @@ -72782,6 +73245,17 @@ var ts; return ts.createCompilerDiagnostic(message, spec); } } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } /** * Gets directories in a set of include patterns that should be watched for changes. */ @@ -72945,7 +73419,7 @@ var ts; (function (ts) { var ScriptSnapshot; (function (ScriptSnapshot) { - var StringScriptSnapshot = (function () { + var StringScriptSnapshot = /** @class */ (function () { function StringScriptSnapshot(text) { this.text = text; } @@ -72969,7 +73443,7 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); - var TextChange = (function () { + var TextChange = /** @class */ (function () { function TextChange() { } return TextChange; @@ -73831,8 +74305,14 @@ var ts; } } ts.findNextToken = findNextToken; + /** + * Finds the rightmost token satisfying `token.end <= position`, + * excluding `JsxText` tokens containing only whitespace. + */ function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { - return find(startNode || sourceFile); + var result = find(startNode || sourceFile); + ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); + return result; function findRightmostToken(n) { if (ts.isToken(n)) { return n; @@ -73848,18 +74328,16 @@ var ts; var children = n.getChildren(); for (var i = 0; i < children.length; i++) { var child = children[i]; - // condition 'position < child.end' checks if child node end after the position - // in the example below this condition will be false for 'aaaa' and 'bbbb' and true for 'ccc' - // aaaa___bbbb___$__ccc - // after we found child node with end after the position we check if start of the node is after the position. - // if yes - then position is in the trivia and we need to look into the previous child to find the token in question. - // if no - position is in the node itself so we should recurse in it. - // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). - // if this is the case - then we should assume that token in question is located in previous child. - if (position < child.end && (nodeHasTokens(child) || child.kind === 10 /* JsxText */)) { + // Note that the span of a node's tokens is [node.getStart(...), node.end). + // Given that `position < child.end` and child has constituent tokens, we distinguish these cases: + // 1) `position` precedes `child`'s tokens or `child` has no tokens (ie: in a comment or whitespace preceding `child`): + // we need to find the last token in a previous child. + // 2) `position` is within the same span: we recurse on `child`. + if (position < child.end) { var start = child.getStart(sourceFile, includeJsDoc); - var lookInPreviousChild = (start >= position) || - (child.kind === 10 /* JsxText */ && start === child.end); // whitespace only JsxText + var lookInPreviousChild = (start >= position) || // cursor in the leading trivia + !nodeHasTokens(child) || + isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); @@ -73881,10 +74359,16 @@ var ts; return candidate && findRightmostToken(candidate); } } - /// finds last node that is considered as candidate for search (isCandidate(node) === true) starting from 'exclusiveStartPosition' + /** + * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. + */ function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { for (var i = exclusiveStartPosition - 1; i >= 0; i--) { - if (nodeHasTokens(children[i])) { + var child = children[i]; + if (isWhiteSpaceOnlyJsxText(child)) { + ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + } + else if (nodeHasTokens(children[i])) { return children[i]; } } @@ -73942,6 +74426,10 @@ var ts; return false; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isWhiteSpaceOnlyJsxText(node) { + return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; + } + ts.isWhiteSpaceOnlyJsxText = isWhiteSpaceOnlyJsxText; function isInTemplateString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); @@ -73954,39 +74442,9 @@ var ts; * @param predicate Additional predicate to test on the comment range. */ function isInComment(sourceFile, position, tokenAtPosition, predicate) { - if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } - return position <= tokenAtPosition.getStart(sourceFile) && - (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || - isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); - function isInCommentRange(commentRanges) { - return ts.forEach(commentRanges, function (c) { return isPositionInCommentRange(c, position, sourceFile.text) && (!predicate || predicate(c)); }); - } + return !!ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ false, /*precedingToken*/ undefined, tokenAtPosition, predicate); } 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): - // - // // asdf ^\n - // - // But for multi-line comments, we don't want to be inside the comment in the following case: - // - // /* asdf */^ - // - // Internally, we represent the end of the comment at the newline and closing '/', respectively. - 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; - } - } function hasDocComment(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // First, we have to see if this position actually landed in a comment. @@ -74000,7 +74458,7 @@ var ts; ts.hasDocComment = hasDocComment; function nodeHasTokens(n) { // If we have a token or node that has a non-zero width, it must have tokens. - // Note, that getWidth() does not take trivia into account. + // Note: getWidth() does not take trivia into account. return n.getWidth() !== 0; } function getNodeModifiers(node) { @@ -74357,6 +74815,7 @@ var ts; } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + flags |= 65536 /* UseAliasDefinedOutsideCurrentScope */; return mapToDisplayParts(function (writer) { typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); }); @@ -74666,11 +75125,11 @@ var ts; templateStack.pop(); } else { - ts.Debug.assert(token === 15 /* TemplateMiddle */, "Should have been a template middle. Was " + token); + ts.Debug.assertEqual(token, 15 /* TemplateMiddle */, "Should have been a template middle."); } } else { - ts.Debug.assert(lastTemplateStackToken === 17 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); + ts.Debug.assertEqual(lastTemplateStackToken, 17 /* OpenBraceToken */, "Should have been an open brace"); templateStack.pop(); } } @@ -76652,7 +77111,7 @@ var ts; if (!typeForObject) return false; // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. - typeMembers = typeChecker.getPropertiesOfType(typeForObject); + typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24 /* NonPublicAccessibilityModifier */); }); existingMembers = objectLikeContainer.elements; } } @@ -76916,11 +77375,11 @@ var ts; return containingNodeKind === 226 /* VariableDeclaration */ || containingNodeKind === 227 /* VariableDeclarationList */ || containingNodeKind === 208 /* VariableStatement */ || - containingNodeKind === 232 /* EnumDeclaration */ || + containingNodeKind === 232 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 230 /* InterfaceDeclaration */ || - containingNodeKind === 175 /* ArrayBindingPattern */ || - containingNodeKind === 231 /* TypeAliasDeclaration */ || + containingNodeKind === 230 /* InterfaceDeclaration */ || // interface A undefined); => should get use to the declaration in file "./foo" + // + // function bar(onfulfilled: (value: T) => void) { //....} + // interface Test { + // pr/*destination*/op1: number + // } + // bar(({pr/*goto*/op1})=>{}); + if (ts.isPropertyName(node) && ts.isBindingElement(node.parent) && ts.isObjectBindingPattern(node.parent.parent) && + (node === (node.parent.propertyName || node.parent.name))) { + var type = typeChecker.getTypeAtLocation(node.parent.parent); + if (type) { + var propSymbols = ts.getPropertySymbolsFromType(type, node); + if (propSymbols) { + return ts.flatMap(propSymbols, function (propSymbol) { return getDefinitionFromSymbol(typeChecker, propSymbol, node); }); + } + } + } // 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 @@ -80614,12 +81104,20 @@ var ts; "crypto", "stream", "util", "assert", "tty", "domain", "constants", "process", "v8", "timers", "console" ]; - var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); + var nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); function loadSafeList(host, safeListPath) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); return ts.createMapFromTemplate(result.config); } JsTyping.loadSafeList = loadSafeList; + function loadTypesMap(host, typesMapPath) { + var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); + if (result.config) { + return ts.createMapFromTemplate(result.config.simpleMap); + } + return undefined; + } + JsTyping.loadTypesMap = loadTypesMap; /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -80812,8 +81310,8 @@ var ts; if (!matches) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. if (patternMatcher.patternContainsDots) { @@ -81549,13 +82047,18 @@ var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { + var collapseText = "..."; + var maxDepth = 20; function collectElements(sourceFile, cancellationToken) { var elements = []; - var collapseText = "..."; - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { + var depth = 0; + walk(sourceFile); + return elements; + /** If useFullStart is true, then the collapsing span includes leading whitespace, including linebreaks. */ + function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { if (hintSpanNode && startElement && endElement) { var span_13 = { - textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), + textSpan: ts.createTextSpanFromBounds(useFullStart ? startElement.getFullStart() : startElement.getStart(), endElement.getEnd()), hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), bannerText: collapseText, autoCollapse: autoCollapse, @@ -81619,8 +82122,6 @@ var ts; function autoCollapse(node) { return ts.isFunctionBlock(node) && node.parent.kind !== 187 /* ArrowFunction */; } - var depth = 0; - var maxDepth = 20; function walk(n) { cancellationToken.throwIfCancellationRequested(); if (depth > maxDepth) { @@ -81633,8 +82134,8 @@ var ts; case 207 /* Block */: if (!ts.isFunctionBlock(n)) { var parent = n.parent; - var openBrace = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); + var openBrace_1 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); + var closeBrace_1 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. @@ -81646,20 +82147,20 @@ var ts; parent.kind === 213 /* WhileStatement */ || parent.kind === 220 /* WithStatement */ || parent.kind === 260 /* CatchClause */) { - addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); break; } if (parent.kind === 224 /* TryStatement */) { // Could be the try-block, or the finally-block. var tryStatement = parent; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); break; } else if (tryStatement.finallyBlock === n) { var finallyKeyword = ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile); if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(finallyKeyword, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); break; } } @@ -81678,33 +82179,38 @@ var ts; } // falls through case 234 /* ModuleBlock */: { - var openBrace = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + var openBrace_2 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); + var closeBrace_2 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n.parent, openBrace_2, closeBrace_2, autoCollapse(n), /*useFullStart*/ true); break; } case 229 /* ClassDeclaration */: case 230 /* InterfaceDeclaration */: case 232 /* EnumDeclaration */: - case 178 /* ObjectLiteralExpression */: case 235 /* CaseBlock */: { - var openBrace = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); + var openBrace_3 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); + var closeBrace_3 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n, openBrace_3, closeBrace_3, autoCollapse(n), /*useFullStart*/ true); break; } + // If the block has no leading keywords and is inside an array literal, + // we only want to collapse the span of the block. + // Otherwise, the collapsed section will include the end of the previous line. + case 178 /* ObjectLiteralExpression */: + var openBrace = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n), /*useFullStart*/ !ts.isArrayLiteralExpression(n.parent)); + break; case 177 /* ArrayLiteralExpression */: var openBracket = ts.findChildOfKind(n, 21 /* OpenBracketToken */, sourceFile); var closeBracket = ts.findChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); + addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n), /*useFullStart*/ !ts.isArrayLiteralExpression(n.parent)); break; } depth++; ts.forEachChild(n, walk); depth--; } - walk(sourceFile); - return elements; } OutliningElementsCollector.collectElements = collectElements; })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); @@ -82760,8 +83266,8 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - for (var _b = 0, declarations_13 = declarations; _b < declarations_13.length; _b++) { - var declaration = declarations_13[_b]; + for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { + var declaration = declarations_12[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -82820,7 +83326,9 @@ var ts; } var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; var argumentCount = getArgumentCount(list); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } @@ -82942,7 +83450,9 @@ var ts; var argumentCount = tagExpression.template.kind === 13 /* NoSubstitutionTemplateLiteral */ ? 1 : tagExpression.template.templateSpans.length + 1; - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } return { kind: 2 /* TaggedTemplateArguments */, invocation: tagExpression, @@ -83060,7 +83570,9 @@ var ts; tags: candidateSignature.getJsDocTags() }; }); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } var selectedItemIndex = candidates.indexOf(resolvedSignature); ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; @@ -83209,114 +83721,112 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (type) { - if (location.parent && location.parent.kind === 179 /* PropertyAccessExpression */) { - var right = location.parent.name; - // Either the location is on the right of a property access, or on the left and the right is missing - if (right === location || (right && right.getFullWidth() === 0)) { - location = location.parent; + if (location.parent && location.parent.kind === 179 /* PropertyAccessExpression */) { + var right = location.parent.name; + // Either the location is on the right of a property access, or on the left and the right is missing + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + // try get the call/construct signature from the type if it matches + var callExpressionLike = void 0; + if (ts.isCallOrNewExpression(location)) { + callExpressionLike = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpressionLike = location.parent; + } + else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { + callExpressionLike = location.parent; + } + if (callExpressionLike) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); + if (!signature && candidateSignatures.length) { + // Use the first candidate: + signature = candidateSignatures[0]; + } + var useConstructSignatures = callExpressionLike.kind === 182 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + // Get the first signature if there is one -- allSignatures may contain + // either the original signature or its target, so check for either + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { + // Constructor + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } - } - // try get the call/construct signature from the type if it matches - var callExpressionLike = void 0; - if (ts.isCallOrNewExpression(location)) { - callExpressionLike = location; - } - else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { - callExpressionLike = location.parent; - } - else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) { - callExpressionLike = location.parent; - } - if (callExpressionLike) { - var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); - if (!signature && candidateSignatures.length) { - // Use the first candidate: - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpressionLike.kind === 182 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); - var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { - // Get the first signature if there is one -- allSignatures may contain - // either the original signature or its target, so check for either - signature = allSignatures.length ? allSignatures[0] : undefined; - } - if (signature) { - if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { - // Constructor - symbolKind = "constructor" /* constructorImplementationElement */; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + else if (symbolFlags & 2097152 /* Alias */) { + symbolKind = "alias" /* alias */; + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(94 /* NewKeyword */)); + displayParts.push(ts.spacePart()); } - else if (symbolFlags & 2097152 /* Alias */) { - symbolKind = "alias" /* alias */; - pushTypePart(symbolKind); + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case "JSX attribute" /* jsxAttribute */: + case "property" /* memberVariableElement */: + case "var" /* variableElement */: + case "const" /* constElement */: + case "let" /* letElement */: + case "parameter" /* parameterElement */: + case "local var" /* localVariableElement */: + // If it is call or construct signature of lambda's write type name + displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - addFullSymbolName(symbol); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - switch (symbolKind) { - case "JSX attribute" /* jsxAttribute */: - case "property" /* memberVariableElement */: - case "var" /* variableElement */: - case "const" /* constElement */: - case "let" /* letElement */: - case "parameter" /* parameterElement */: - case "local var" /* localVariableElement */: - // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(56 /* ColonToken */)); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94 /* NewKeyword */)); - displayParts.push(ts.spacePart()); - } - if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); - } - addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); - break; - default: - // Just signature - addSignatureDisplayParts(signature, allSignatures); - } - hasAddedSymbolInfo = true; + if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + } + addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); + break; + default: + // Just signature + addSignatureDisplayParts(signature, allSignatures); } + hasAddedSymbolInfo = true; } - else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 152 /* Constructor */)) { - // get the signature from the declaration and write it - var functionDeclaration_1 = location.parent; - // Use function declaration to write the signatures only if the symbol corresponding to this declaration - var locationIsSymbolDeclaration = ts.findDeclaration(symbol, function (declaration) { - return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); - }); - if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 152 /* Constructor */ ? 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 /* Constructor */) { - // show (constructor) Type(...) signature - symbolKind = "constructor" /* constructorImplementationElement */; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 /* CallSignature */ && - !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration + (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 152 /* Constructor */)) { + // get the signature from the declaration and write it + var functionDeclaration_1 = location.parent; + // Use function declaration to write the signatures only if the symbol corresponding to this declaration + var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); + }); + if (locationIsSymbolDeclaration) { + var allSignatures = functionDeclaration_1.kind === 152 /* Constructor */ ? 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 /* Constructor */) { + // show (constructor) Type(...) signature + symbolKind = "constructor" /* constructorImplementationElement */; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 /* CallSignature */ && + !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; } } } @@ -83502,7 +84012,9 @@ var ts; symbolFlags & 98304 /* Accessor */ || symbolKind === "method" /* memberFunctionElement */) { var allSignatures = type.getNonNullableType().getCallSignatures(); - addSignatureDisplayParts(allSignatures[0], allSignatures); + if (allSignatures.length) { + addSignatureDisplayParts(allSignatures[0], allSignatures); + } } } } @@ -83676,11 +84188,11 @@ var ts; getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, writeFile: function (name, text) { if (ts.fileExtensionIs(name, ".map")) { - ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); + ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name); sourceMapText = text; } else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); + ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name); outputText = text; } }, @@ -84005,7 +84517,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var FormattingContext = (function () { + var FormattingContext = /** @class */ (function () { function FormattingContext(sourceFile, formattingRequestKind, options) { this.sourceFile = sourceFile; this.formattingRequestKind = formattingRequestKind; @@ -84104,7 +84616,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var Rule = (function () { + var Rule = /** @class */ (function () { function Rule(Descriptor, Operation, Flag) { if (Flag === void 0) { Flag = 0 /* None */; } this.Descriptor = Descriptor; @@ -84142,7 +84654,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var RuleDescriptor = (function () { + var RuleDescriptor = /** @class */ (function () { function RuleDescriptor(LeftTokenRange, RightTokenRange) { this.LeftTokenRange = LeftTokenRange; this.RightTokenRange = RightTokenRange; @@ -84187,7 +84699,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var RuleOperation = (function () { + var RuleOperation = /** @class */ (function () { function RuleOperation(Context, Action) { this.Context = Context; this.Action = Action; @@ -84213,7 +84725,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var RuleOperationContext = (function () { + var RuleOperationContext = /** @class */ (function () { function RuleOperationContext() { var funcs = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -84248,7 +84760,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var Rules = (function () { + var Rules = /** @class */ (function () { function Rules() { /// /// Common Rules @@ -84407,6 +84919,7 @@ var ts; // Insert space after opening and before closing nonempty parenthesis this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenOpenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenParenToken */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenParenToken */, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); @@ -84486,7 +84999,7 @@ var ts; this.SpaceAfterComma, this.NoSpaceAfterComma, this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, - this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, + this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.SpaceBetweenOpenParens, 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, @@ -84825,7 +85338,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var RulesMap = (function () { + var RulesMap = /** @class */ (function () { function RulesMap() { this.map = []; this.mapRowLength = 0; @@ -84895,7 +85408,7 @@ var ts; RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; })(RulesPosition = formatting.RulesPosition || (formatting.RulesPosition = {})); - var RulesBucketConstructionState = (function () { + var RulesBucketConstructionState = /** @class */ (function () { function RulesBucketConstructionState() { //// The Rules list contains all the inserted rules into a rulebucket in the following order: //// 1- Ignore rules with specific token combination @@ -84936,7 +85449,7 @@ var ts; return RulesBucketConstructionState; }()); formatting.RulesBucketConstructionState = RulesBucketConstructionState; - var RulesBucket = (function () { + var RulesBucket = /** @class */ (function () { function RulesBucket() { this.rules = []; } @@ -84985,7 +85498,7 @@ var ts; for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { allTokens.push(token); } - var TokenValuesAccess = (function () { + var TokenValuesAccess = /** @class */ (function () { function TokenValuesAccess(tokens) { if (tokens === void 0) { tokens = []; } this.tokens = tokens; @@ -84999,7 +85512,7 @@ var ts; TokenValuesAccess.prototype.isSpecific = function () { return true; }; return TokenValuesAccess; }()); - var TokenSingleValueAccess = (function () { + var TokenSingleValueAccess = /** @class */ (function () { function TokenSingleValueAccess(token) { this.token = token; } @@ -85012,7 +85525,7 @@ var ts; TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; return TokenSingleValueAccess; }()); - var TokenAllAccess = (function () { + var TokenAllAccess = /** @class */ (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { @@ -85027,7 +85540,7 @@ var ts; TokenAllAccess.prototype.isSpecific = function () { return false; }; return TokenAllAccess; }()); - var TokenAllExceptAccess = (function () { + var TokenAllExceptAccess = /** @class */ (function () { function TokenAllExceptAccess(except) { this.except = except; } @@ -85119,7 +85632,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var RulesProvider = (function () { + var RulesProvider = /** @class */ (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); @@ -85427,7 +85940,6 @@ 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, options); - var previousRangeHasError; var previousRange; var previousParent; var previousRangeStartLine; @@ -85818,7 +86330,7 @@ var ts; function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAdded; - if (!rangeHasError && !previousRangeHasError) { + if (!rangeHasError) { if (!previousRange) { // trim whitespaces starting from the beginning of the span up to the current line var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); @@ -85832,7 +86344,6 @@ var ts; previousRange = range; previousParent = parent; previousRangeStartLine = rangeStart.line; - previousRangeHasError = rangeHasError; return lineAdded; } function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { @@ -86038,6 +86549,51 @@ var ts; } } } + /** + * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. + */ + function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, // tslint:disable-line:no-null-keyword + tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } + var tokenStart = tokenAtPosition.getStart(sourceFile); + if (tokenStart <= position && position < tokenAtPosition.getEnd()) { + return undefined; + } + if (precedingToken === undefined) { + precedingToken = ts.findPrecedingToken(position, sourceFile); + } + // Between two consecutive tokens, all comments are either trailing on the former + // or leading on the latter (and none are in both lists). + var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end); + var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); + var commentRanges = trailingRangesOfPreviousToken && leadingCommentRangesOfNextToken ? + trailingRangesOfPreviousToken.concat(leadingCommentRangesOfNextToken) : + trailingRangesOfPreviousToken || leadingCommentRangesOfNextToken; + if (commentRanges) { + for (var _i = 0, commentRanges_1 = commentRanges; _i < commentRanges_1.length; _i++) { + var range = commentRanges_1[_i]; + // The end marker of a single-line comment does not include the newline character. + // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position): + // + // // asdf ^\n + // + // But for closed multi-line comments, we don't want to be inside the comment in the following case: + // + // /* asdf */^ + // + // However, unterminated multi-line comments *do* contain their end. + // + // Internally, we represent the end of the comment at the newline and closing '/', respectively. + // + if ((range.pos < position && position < range.end || + position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()))) { + return (range.kind === 3 /* MultiLineCommentTrivia */ || !onlyMultiLine) && (!predicate || predicate(range)) ? range : undefined; + } + } + } + return undefined; + } + formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { case 152 /* Constructor */: @@ -86165,12 +86721,28 @@ var ts; return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ true, precedingToken || null); // tslint:disable-line:no-null-keyword + if (enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; + } if (!precedingToken) { return getBaseIndentation(options); } // no indentation in string \regex\template literals var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); - if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) { + if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) { return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; @@ -86473,13 +87045,13 @@ var ts; var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options); } - /* - Character is the actual index of the character since the beginning of the line. - Column - position of the character after expanding tabs to spaces - "0\t2$" - value of 'character' for '$' is 3 - value of 'column' for '$' is 6 (assuming that tab size is 4) - */ + /** + * Character is the actual index of the character since the beginning of the line. + * Column - position of the character after expanding tabs to spaces. + * "0\t2$" + * value of 'character' for '$' is 3 + * value of 'column' for '$' is 6 (assuming that tab size is 4) + */ function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { var character = 0; var column = 0; @@ -86633,6 +87205,12 @@ var ts; } return false; } + var ChangeKind; + (function (ChangeKind) { + ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; + ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; + ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + })(ChangeKind || (ChangeKind = {})); function getSeparatorCharacter(separator) { return ts.tokenToString(separator.kind); } @@ -86666,13 +87244,11 @@ var ts; } textChanges.getAdjustedStartPosition = getAdjustedStartPosition; function getAdjustedEndPosition(sourceFile, node, options) { - if (options.useNonAdjustedEndPosition) { + if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { return node.getEnd(); } var end = node.getEnd(); var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); - // check if last character before newPos is linebreak - // if yes - considered all skipped trivia to be trailing trivia of the node return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) ? newEnd : end; @@ -86691,7 +87267,10 @@ var ts; } return s; } - var ChangeTracker = (function () { + function getNewlineKind(context) { + return context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + } + var ChangeTracker = /** @class */ (function () { function ChangeTracker(newLine, rulesProvider, validator) { this.newLine = newLine; this.rulesProvider = rulesProvider; @@ -86700,24 +87279,24 @@ var ts; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromCodeFixContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.rulesProvider); + return new ChangeTracker(getNewlineKind(context), context.rulesProvider); + }; + ChangeTracker.prototype.deleteRange = function (sourceFile, range) { + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); + return this; }; ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, node, options); - this.changes.push({ sourceFile: sourceFile, options: options, range: { pos: startPosition, end: endPosition } }); - return this; - }; - ChangeTracker.prototype.deleteRange = function (sourceFile, range) { - this.changes.push({ sourceFile: sourceFile, range: range }); + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); return this; }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, range: { pos: startPosition, end: endPosition } }); + this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); return this; }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { @@ -86756,33 +87335,68 @@ var ts; }; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ sourceFile: sourceFile, range: range, options: options, node: newNode }); + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); return this; }; ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: endPosition } }); - return this; + return this.replaceWithSingle(sourceFile, startPosition, endPosition, newNode, options); }; ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: endPosition } }); + return this.replaceWithSingle(sourceFile, startPosition, endPosition, newNode, options); + }; + ChangeTracker.prototype.replaceWithSingle = function (sourceFile, startPosition, endPosition, newNode, options) { + this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, + sourceFile: sourceFile, + options: options, + node: newNode, + range: { pos: startPosition, end: endPosition } + }); return this; }; + ChangeTracker.prototype.replaceWithMultiple = function (sourceFile, startPosition, endPosition, newNodes, options) { + this.changes.push({ + kind: ChangeKind.ReplaceWithMultipleNodes, + sourceFile: sourceFile, + options: options, + nodes: newNodes, + range: { pos: startPosition, end: endPosition } + }); + return this; + }; + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; + ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, oldNodes[0], options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, ts.lastOrUndefined(oldNodes), options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; + ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { + return this.replaceWithMultiple(sourceFile, range.pos, range.end, newNodes, options); + }; + ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); + var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); + return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); return this; }; ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, before, options, Position.Start); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: startPosition } }); - return this; + return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, options); }; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { if (options === void 0) { options = {}; } @@ -86794,6 +87408,7 @@ var ts; // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: {}, range: { pos: after.end, end: after.end }, @@ -86802,8 +87417,7 @@ var ts; } } var endPosition = getAdjustedEndPosition(sourceFile, after, options); - this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: endPosition, end: endPosition } }); - return this; + return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, options); }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, @@ -86869,10 +87483,10 @@ var ts; startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); } this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: startPos, end: containingList[index + 1].getStart(sourceFile) }, node: newNode, - useIndentationFromFile: true, options: { prefix: prefix, // write separator and leading trivia of the next element as suffix @@ -86911,6 +87525,7 @@ var ts; if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: end, end: end }, node: ts.createToken(separator), @@ -86924,6 +87539,7 @@ var ts; insertPos--; } this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: insertPos, end: insertPos }, node: newNode, @@ -86932,6 +87548,7 @@ var ts; } else { this.changes.push({ + kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: { pos: end, end: end }, node: newNode, @@ -86973,34 +87590,46 @@ var ts; return ts.createTextSpanFromBounds(change.range.pos, change.range.end); }; ChangeTracker.prototype.computeNewText = function (change, sourceFile) { - if (!change.node) { + var _this = this; + if (change.kind === ChangeKind.Remove) { // deletion case return ""; } var options = change.options || {}; - var nonFormattedText = getNonformattedText(change.node, sourceFile, this.newLine); - if (this.validator) { - this.validator(nonFormattedText); - } - var formatOptions = this.rulesProvider.getFormatOptions(); + var text; var pos = change.range.pos; var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - var initialIndentation = change.options.indentation !== undefined - ? change.options.indentation - : change.useIndentationFromFile - ? ts.formatting.SmartIndenter.getIndentation(change.range.pos, sourceFile, formatOptions, posStartsLine || (change.options.prefix === this.newLineCharacter)) - : 0; - var delta = change.options.delta !== undefined - ? change.options.delta - : ts.formatting.SmartIndenter.shouldIndentChildNode(change.node) - ? formatOptions.indentSize - : 0; - var text = applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, this.rulesProvider); + if (change.kind === ChangeKind.ReplaceWithMultipleNodes) { + var parts = change.nodes.map(function (n) { return _this.getFormattedTextOfNode(n, sourceFile, pos, options); }); + text = parts.join(change.options.nodeSeparator); + } + else { + ts.Debug.assert(change.kind === ChangeKind.ReplaceWithSingleNode, "change.kind === ReplaceWithSingleNode"); + text = this.getFormattedTextOfNode(change.node, sourceFile, pos, options); + } // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line - // however keep indentation if it is was forced - text = posStartsLine || change.options.indentation !== undefined ? text : text.replace(/^\s+/, ""); + text = (posStartsLine || options.indentation !== undefined) ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + text + (options.suffix || ""); }; + ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) { + var nonformattedText = getNonformattedText(node, sourceFile, this.newLine); + if (this.validator) { + this.validator(nonformattedText); + } + var formatOptions = this.rulesProvider.getFormatOptions(); + var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; + var initialIndentation = options.indentation !== undefined + ? options.indentation + : (options.useIndentationFromFile !== false) + ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter)) + : 0; + var delta = options.delta !== undefined + ? options.delta + : ts.formatting.SmartIndenter.shouldIndentChildNode(node) + ? (formatOptions.indentSize || 0) + : 0; + return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.rulesProvider); + }; ChangeTracker.normalize = function (changes) { // order changes by start position var normalized = ts.stableSort(changes, function (a, b) { return a.range.pos - b.range.pos; }); @@ -87065,7 +87694,7 @@ var ts; nodeArray.end = getEnd(nodes); return nodeArray; } - var Writer = (function () { + var Writer = /** @class */ (function () { function Writer(newLine) { var _this = this; this.lastNonTriviaPosition = 0; @@ -87948,7 +88577,7 @@ var ts; ModuleSpecifierComparison[ModuleSpecifierComparison["Equal"] = 1] = "Equal"; ModuleSpecifierComparison[ModuleSpecifierComparison["Worse"] = 2] = "Worse"; })(ModuleSpecifierComparison || (ModuleSpecifierComparison = {})); - var ImportCodeActionMap = (function () { + var ImportCodeActionMap = /** @class */ (function () { function ImportCodeActionMap() { this.symbolIdToActionMap = []; } @@ -88061,7 +88690,7 @@ var ts; } else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - symbol = checker.getAliasedSymbol(checker.resolveNameAtLocation(token, checker.getJsxNamespace(), 107455 /* Value */)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455 /* Value */)); symbolName = symbol.name; } else { @@ -88086,7 +88715,7 @@ var ts; if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { // check if this symbol is already used var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isDefault*/ true)); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isNamespaceImport*/ true)); } } // "default" is a keyword and not a legal identifier for the import, so we don't expect it here @@ -88162,8 +88791,8 @@ var ts; var namespaceImportDeclaration; var namedImportDeclaration; var existingModuleSpecifier; - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (declaration.kind === 238 /* ImportDeclaration */) { var namedBindings = declaration.importClause && declaration.importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { @@ -88273,9 +88902,11 @@ var ts; : isNamespaceImport ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); + var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); + moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifierLiteral); if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeAt(sourceFile, getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); } else { changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); @@ -88284,6 +88915,46 @@ var ts; // 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, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + function getSourceFileImportLocation(node) { + // For a source file, it is possible there are detached comments we should not skip + var text = node.text; + var ranges = ts.getLeadingCommentRanges(text, 0); + if (!ranges) + return 0; + var position = 0; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end + 1; + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(node.text, range.pos, range.end)) { + position = range.end + 1; + continue; + } + break; + } + return position; + } + function getSingleQuoteStyleFromExistingImports() { + var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { + if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { + if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { + return node.moduleSpecifier; + } + } + else if (ts.isImportEqualsDeclaration(node)) { + if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { + return node.moduleReference.expression; + } + } + }); + if (firstModuleSpecifier) { + return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39 /* singleQuote */; + } + } function getModuleSpecifierForNewImport() { var fileName = sourceFile.fileName; var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; @@ -88415,8 +89086,8 @@ var ts; } function getNodeModulePathParts(fullPath) { // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[otherpackage/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ var topLevelNodeModulesIndex = 0; var topLevelPackageNameIndex = 0; var packageRootIndex = 0; @@ -88425,7 +89096,8 @@ var ts; (function (States) { States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; States[States["NodeModules"] = 1] = "NodeModules"; - States[States["PackageContent"] = 2] = "PackageContent"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; })(States || (States = {})); var partStart = 0; var partEnd = 0; @@ -88442,15 +89114,21 @@ var ts; } break; case 1 /* NodeModules */: - packageRootIndex = partEnd; - state = 2 /* PackageContent */; + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } break; - case 2 /* PackageContent */: + case 3 /* PackageContent */: if (fullPath.indexOf("/node_modules/", partStart) === partStart) { state = 1 /* NodeModules */; } else { - state = 2 /* PackageContent */; + state = 3 /* PackageContent */; } break; } @@ -88807,231 +89485,1208 @@ var ts; (function (ts) { var refactor; (function (refactor) { - var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); - function getAvailableActions(context) { - if (!ts.isInJavaScriptFile(context.file)) { - return undefined; + var convertFunctionToES6Class; + (function (convertFunctionToES6Class_1) { + var actionName = "convert"; + var convertFunctionToES6Class = { + name: "Convert to ES2015 class", + description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions + }; + refactor.registerRefactor(convertFunctionToES6Class); + function getAvailableActions(context) { + if (!ts.isInJavaScriptFile(context.file)) { + return undefined; + } + var start = context.startPosition; + var node = ts.getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); + var checker = context.program.getTypeChecker(); + var symbol = checker.getSymbolAtLocation(node); + if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = symbol.valueDeclaration.initializer.symbol; + } + if (symbol && (symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { + return [ + { + name: convertFunctionToES6Class.name, + description: convertFunctionToES6Class.description, + actions: [ + { + description: convertFunctionToES6Class.description, + name: actionName + } + ] + } + ]; + } } - var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - var symbol = checker.getSymbolAtLocation(node); - if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = symbol.valueDeclaration.initializer.symbol; - } - if (symbol && (symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { - return [ - { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, - actions: [ - { - description: convertFunctionToES6Class.description, - name: actionName - } - ] + function getEditsForAction(context, action) { + // Somehow wrong action got invoked? + if (actionName !== action) { + return undefined; + } + var start = context.startPosition; + var sourceFile = context.file; + var checker = context.program.getTypeChecker(); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var ctorSymbol = checker.getSymbolAtLocation(token); + var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var deletedNodes = []; + var deletes = []; + if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + return undefined; + } + 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 undefined; + } + // 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 { + edits: 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; } - ]; - } - } - function getEditsForAction(context, action) { - // Somehow wrong action got invoked? - if (actionName !== action) { - return undefined; - } - var start = context.startPosition; - var sourceFile = context.file; - var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var ctorSymbol = checker.getSymbolAtLocation(token); - var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; - var deletedNodes = []; - var deletes = []; - if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { - return undefined; - } - 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); + deletedNodes.push(node); + if (inList) { + deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); } else { - deleteNode(ctorDeclaration, /*inList*/ true); + deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); } - newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); - break; - } - if (!newClassDeclaration) { - return undefined; - } - // 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 { - edits: 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); }); + 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; + var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + copyComments(assignmentBinaryExpression, method); + return method; + } + 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)]); + } + var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + copyComments(assignmentBinaryExpression, method); + return method; + } + default: { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop); + return prop; + } + } + } + } + function copyComments(sourceNode, targetNode) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // Remove leading /* + pos += 2; + // Remove trailing */ + end -= 2; + } + else { + // Remove leading // + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + }); + } + 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)); + } + var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; + } + } + })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/// +/// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var extractMethod; + (function (extractMethod_1) { + var extractMethod = { + name: "Extract Method", + description: ts.Diagnostics.Extract_function.message, + getAvailableActions: getAvailableActions, + getEditsForAction: getEditsForAction, + }; + refactor.registerRefactor(extractMethod); + /** Compute the associated code actions */ + function getAvailableActions(context) { + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: context.endPosition - context.startPosition }); + var targetRange = rangeToExtract.targetRange; + if (targetRange === undefined) { + return undefined; + } + var extractions = getPossibleExtractions(targetRange, context); + if (extractions === undefined) { + // No extractions possible + return undefined; + } + var actions = []; + var usedNames = ts.createMap(); + var i = 0; + for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { + var extr = extractions_1[_i]; + // Skip these since we don't have a way to report errors yet + if (extr.errors && extr.errors.length) { + continue; + } + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_function_into_0.message, [extr.scopeDescription]); + if (!usedNames.has(description)) { + usedNames.set(description, true); + actions.push({ + description: description, + name: "scope_" + i + }); + } + // *do* increment i anyway because we'll look for the i-th scope + // later when actually doing the refactoring if the user requests it + i++; + } + if (actions.length === 0) { + return undefined; + } + return [{ + name: extractMethod.name, + description: extractMethod.description, + inlineable: true, + actions: actions + }]; + } + function getEditsForAction(context, actionName) { + var length = context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: length }); + var targetRange = rangeToExtract.targetRange; + var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); + ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); + var index = +parsedIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); + var extractions = getPossibleExtractions(targetRange, context, index); + // Scope is no longer valid from when the user issued the refactor (??) + ts.Debug.assert(extractions !== undefined, "The extraction went missing? How?"); + return ({ edits: extractions[0].changes }); + } + // Move these into diagnostic messages if they become user-facing + var Messages; + (function (Messages) { + function createMessage(message) { + return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; + } + Messages.CannotExtractFunction = createMessage("Cannot extract function."); + Messages.StatementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.CannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.TypeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.InsufficientSelection = createMessage("Select more than a single identifier."); + Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); + Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + })(Messages || (Messages = {})); + var RangeFacts; + (function (RangeFacts) { + RangeFacts[RangeFacts["None"] = 0] = "None"; + RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn"; + RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis"; + /** + * The range is in a function which needs the 'static' modifier in a class + */ + RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; + })(RangeFacts = extractMethod_1.RangeFacts || (extractMethod_1.RangeFacts = {})); + /** + * getRangeToExtract takes a span inside a text file and returns either an expression or an array + * of statements representing the minimum set of nodes needed to extract the entire span. This + * process may fail, in which case a set of errors is returned instead (these are currently + * not shown to the user, but can be used by us diagnostically) + */ + function getRangeToExtract(sourceFile, span) { + var length = span.length || 0; + // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. + // This may fail (e.g. you select two statements in the root of a source file) + var start = getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false), sourceFile, span); + // Do the same for the ending position + var end = getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); + var declarations = []; + // We'll modify these flags as we walk the tree to collect data + // about what things need to be done as part of the extraction. + var rangeFacts = RangeFacts.None; + if (!start || !end) { + // cannot find either start or end node + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractFunction)] }; + } + if (start.parent !== end.parent) { + // handle cases like 1 + [2 + 3] + 4 + // user selection is marked with []. + // in this case 2 + 3 does not belong to the same tree node + // instead the shape of the tree looks like this: + // + + // / \ + // + 4 + // / \ + // + 3 + // / \ + // 1 2 + // in this case there is no such one node that covers ends of selection and is located inside the selection + // to handle this we check if both start and end of the selection belong to some binary operation + // and start node is parented by the parent of the end node + // if this is the case - expand the selection to the entire parent of end node (in this case it will be [1 + 2 + 3] + 4) + var startParent = ts.skipParentheses(start.parent); + var endParent = ts.skipParentheses(end.parent); + if (ts.isBinaryExpression(startParent) && ts.isBinaryExpression(endParent) && ts.isNodeDescendantOf(startParent, endParent)) { + start = end = endParent; + } + else { + // start and end nodes belong to different subtrees + return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + } + } + if (start !== end) { + // start and end should be statements and parent should be either block or a source file + if (!isBlockLike(start.parent)) { + return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + } + var statements = []; + for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement === start || statements.length) { + var errors = checkNode(statement); + if (errors) { + return { errors: errors }; + } + statements.push(statement); + } + if (statement === end) { + break; + } + } + return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } 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; + // We have a single node (start) + var errors = checkRootNode(start) || checkNode(start); + if (errors) { + return { errors: errors }; } - var memberDeclaration = symbol.valueDeclaration; - var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - return; + // If our selection is the expression in an ExpressionStatement, expand + // the selection to include the enclosing Statement (this stops us + // from trying to care about the return value of the extracted function + // and eliminates double semicolon insertion in certain scenarios) + var range = ts.isStatement(start) + ? [start] + : start.parent && start.parent.kind === 210 /* ExpressionStatement */ + ? [start.parent] + : start; + return { targetRange: { range: range, facts: rangeFacts, declarations: declarations } }; + } + function createErrorResult(sourceFile, start, length, message) { + return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; + } + function checkRootNode(node) { + if (ts.isIdentifier(node)) { + return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; } - // 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); + return undefined; + } + function checkForStaticContext(nodeToCheck, containingClass) { + var current = nodeToCheck; + while (current !== containingClass) { + if (current.kind === 149 /* PropertyDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 146 /* Parameter */) { + var ctorOrMethod = ts.getContainingFunction(current); + if (ctorOrMethod.kind === 152 /* Constructor */) { + rangeFacts |= RangeFacts.InStaticRegion; + } + break; + } + else if (current.kind === 151 /* MethodDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { + rangeFacts |= RangeFacts.InStaticRegion; + } + } + current = current.parent; } - switch (assignmentBinaryExpression.right.kind) { - case 186 /* FunctionExpression */: { - var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - copyComments(assignmentBinaryExpression, method); - return method; + } + // Verifies whether we can actually extract this node or not. + function checkNode(nodeToCheck) { + var PermittedJumps; + (function (PermittedJumps) { + PermittedJumps[PermittedJumps["None"] = 0] = "None"; + PermittedJumps[PermittedJumps["Break"] = 1] = "Break"; + PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; + PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + if (!ts.isStatement(nodeToCheck) && !(ts.isExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; + } + if (ts.isInAmbientContext(nodeToCheck)) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.CannotExtractAmbientBlock)]; + } + // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default) + var containingClass = ts.getContainingClass(nodeToCheck); + if (containingClass) { + checkForStaticContext(nodeToCheck, containingClass); + } + var errors; + var permittedJumps = 4 /* Return */; + var seenLabels; + visit(nodeToCheck); + return errors; + function visit(node) { + if (errors) { + // already found an error - can stop now + return true; } - 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; + if (ts.isDeclaration(node)) { + var declaringNode = (node.kind === 226 /* VariableDeclaration */) ? node.parent.parent : node; + if (ts.hasModifier(declaringNode, 1 /* Export */)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + return true; } - else { - var expression = arrowFunctionBody; - bodyBlock = ts.createBlock([ts.createReturn(expression)]); - } - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - copyComments(assignmentBinaryExpression, method); - return method; + declarations.push(node.symbol); } - default: { - // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { - return; - } - var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, - /*type*/ undefined, assignmentBinaryExpression.right); - copyComments(assignmentBinaryExpression.parent, prop); - return prop; + // Some things can't be extracted in certain situations + switch (node.kind) { + case 238 /* ImportDeclaration */: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + return true; + case 97 /* SuperKeyword */: + // For a super *constructor call*, we have to be extracting the entire class, + // but a super *method call* simply implies a 'this' reference + if (node.parent.kind === 181 /* CallExpression */) { + // Super constructor call + var containingClass_1 = ts.getContainingClass(node); + if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + return true; + } + } + else { + rangeFacts |= RangeFacts.UsesThis; + } + break; } + if (!node || ts.isFunctionLike(node) || ts.isClassLike(node)) { + switch (node.kind) { + case 228 /* FunctionDeclaration */: + case 229 /* ClassDeclaration */: + if (node.parent.kind === 265 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) { + // You cannot extract global declarations + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.FunctionWillNotBeVisibleInTheNewScope)); + } + break; + } + // do not dive into functions or classes + return false; + } + var savedPermittedJumps = permittedJumps; + if (node.parent) { + switch (node.parent.kind) { + case 211 /* IfStatement */: + if (node.parent.thenStatement === node || node.parent.elseStatement === node) { + // forbid all jumps inside thenStatement or elseStatement + permittedJumps = 0 /* None */; + } + break; + case 224 /* TryStatement */: + if (node.parent.tryBlock === node) { + // forbid all jumps inside try blocks + permittedJumps = 0 /* None */; + } + else if (node.parent.finallyBlock === node) { + // allow unconditional returns from finally blocks + permittedJumps = 4 /* Return */; + } + break; + case 260 /* CatchClause */: + if (node.parent.block === node) { + // forbid all jumps inside the block of catch clause + permittedJumps = 0 /* None */; + } + break; + case 257 /* CaseClause */: + if (node.expression !== node) { + // allow unlabeled break inside case clauses + permittedJumps |= 1 /* Break */; + } + break; + default: + if (ts.isIterationStatement(node.parent, /*lookInLabeledStatements*/ false)) { + if (node.parent.statement === node) { + // allow unlabeled break/continue inside loops + permittedJumps |= 1 /* Break */ | 2 /* Continue */; + } + } + break; + } + } + switch (node.kind) { + case 169 /* ThisType */: + case 99 /* ThisKeyword */: + rangeFacts |= RangeFacts.UsesThis; + break; + case 222 /* LabeledStatement */: + { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } + case 218 /* BreakStatement */: + case 217 /* ContinueStatement */: + { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } + else { + if (!(permittedJumps & (218 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } + case 191 /* AwaitExpression */: + rangeFacts |= RangeFacts.IsAsyncFunction; + break; + case 197 /* YieldExpression */: + rangeFacts |= RangeFacts.IsGenerator; + break; + case 219 /* ReturnStatement */: + if (permittedJumps & 4 /* Return */) { + rangeFacts |= RangeFacts.HasReturn; + } + else { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalReturnStatement)); + } + break; + default: + ts.forEachChild(node, visit); + break; + } + permittedJumps = savedPermittedJumps; } } } - function copyComments(sourceNode, targetNode) { - ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { - if (kind === 3 /* MultiLineCommentTrivia */) { - // Remove leading /* - pos += 2; - // Remove trailing */ - end -= 2; + extractMethod_1.getRangeToExtract = getRangeToExtract; + function isValidExtractionTarget(node) { + // Note that we don't use isFunctionLike because we don't want to put the extracted closure *inside* a method + return (node.kind === 228 /* FunctionDeclaration */) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + } + /** + * Computes possible places we could extract the function into. For example, + * you may be able to extract into a class method *or* local closure *or* namespace function, + * depending on what's in the extracted body. + */ + function collectEnclosingScopes(range) { + var current = isReadonlyArray(range.range) ? ts.firstOrUndefined(range.range) : range.range; + if (range.facts & RangeFacts.UsesThis) { + // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class + var containingClass = ts.getContainingClass(current); + if (containingClass) { + return [containingClass]; + } + } + var start = current; + var scopes = undefined; + while (current) { + // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. + // Walk up to the closest parent of a place where we can logically put a sibling: + // * Function declaration + // * Class declaration or expression + // * Module/namespace or source file + if (current !== start && isValidExtractionTarget(current)) { + (scopes = scopes || []).push(current); + } + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current && current.parent && current.parent.kind === 146 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLike(parent); }).parent; } else { - // Remove leading // - pos += 2; + current = current.parent; } - ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + } + return scopes; + } + extractMethod_1.collectEnclosingScopes = collectEnclosingScopes; + /** + * Given a piece of text to extract ('targetRange'), computes a list of possible extractions. + * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes + * or an error explaining why we can't extract into that scope. + */ + function getPossibleExtractions(targetRange, context, requestedChangesIndex) { + if (requestedChangesIndex === void 0) { requestedChangesIndex = undefined; } + var sourceFile = context.file; + if (targetRange === undefined) { + return undefined; + } + var scopes = collectEnclosingScopes(targetRange); + if (scopes === undefined) { + return undefined; + } + var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + var _a = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker()), target = _a.target, usagesPerScope = _a.usagesPerScope, errorsPerScope = _a.errorsPerScope; + context.cancellationToken.throwIfCancellationRequested(); + if (requestedChangesIndex !== undefined) { + if (errorsPerScope[requestedChangesIndex].length) { + return undefined; + } + return [extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context)]; + } + else { + return scopes.map(function (scope, i) { + var errors = errorsPerScope[i]; + if (errors.length) { + return { + scope: scope, + scopeDescription: getDescriptionForScope(scope), + errors: errors + }; + } + return { scope: scope, scopeDescription: getDescriptionForScope(scope) }; + }); + } + } + extractMethod_1.getPossibleExtractions = getPossibleExtractions; + function getDescriptionForScope(scope) { + if (ts.isFunctionLike(scope)) { + switch (scope.kind) { + case 152 /* Constructor */: + return "constructor"; + case 186 /* FunctionExpression */: + return scope.name + ? "function expression " + scope.name.getText() + : "anonymous function expression"; + case 228 /* FunctionDeclaration */: + return "function " + scope.name.getText(); + case 187 /* ArrowFunction */: + return "arrow function"; + case 151 /* MethodDeclaration */: + return "method " + scope.name.getText(); + case 153 /* GetAccessor */: + return "get " + scope.name.getText(); + case 154 /* SetAccessor */: + return "set " + scope.name.getText(); + } + } + else if (ts.isModuleBlock(scope)) { + return "namespace " + scope.parent.name.getText(); + } + else if (ts.isClassLike(scope)) { + return scope.kind === 229 /* ClassDeclaration */ + ? "class " + scope.name.text + : scope.name.text + ? "class expression " + scope.name.text + : "anonymous class expression"; + } + else if (ts.isSourceFile(scope)) { + return "file '" + scope.fileName + "'"; + } + else { + return "unknown"; + } + } + function getUniqueName(isNameOkay) { + var functionNameText = "newFunction"; + if (isNameOkay(functionNameText)) { + return functionNameText; + } + var i = 1; + while (!isNameOkay(functionNameText = "newFunction_" + i)) { + i++; + } + return functionNameText; + } + function extractFunctionInScope(node, scope, _a, range, context) { + var usagesInScope = _a.usages, substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted function + var file = scope.getSourceFile(); + var functionNameText = getUniqueName(function (n) { return !file.identifiers.has(n); }); + var isJS = ts.isInJavaScriptFile(scope); + var functionName = ts.createIdentifier(functionNameText); + var functionReference = ts.createIdentifier(functionNameText); + var returnType = undefined; + var parameters = []; + var callArguments = []; + var writes; + usagesInScope.forEach(function (usage, name) { + var typeNode = undefined; + if (!isJS) { + var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + type = checker.getBaseTypeOfLiteralType(type); + typeNode = checker.typeToTypeNode(type, node, ts.NodeBuilderFlags.NoTruncation); + } + var paramDecl = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ name, + /*questionToken*/ undefined, typeNode); + parameters.push(paramDecl); + if (usage.usage === 2 /* Write */) { + (writes || (writes = [])).push(usage); + } + callArguments.push(ts.createIdentifier(name)); }); + // Provide explicit return types for contexutally-typed functions + // to avoid problems when there are literal types present + if (ts.isExpression(node) && !isJS) { + var contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType); + } + var _b = transformFunctionBody(node), body = _b.body, returnValueProperty = _b.returnValueProperty; + var newFunction; + if (ts.isClassLike(scope)) { + // always create private method in TypeScript files + var modifiers = isJS ? [] : [ts.createToken(112 /* PrivateKeyword */)]; + if (range.facts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(115 /* StaticKeyword */)); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + modifiers.push(ts.createToken(120 /* AsyncKeyword */)); + } + newFunction = ts.createMethod( + /*decorators*/ undefined, modifiers, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, + /*questionToken*/ undefined, + /*typeParameters*/ [], parameters, returnType, body); + } + else { + newFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, + /*typeParameters*/ [], parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + // insert function at the end of the scope + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + var newNodes = []; + // replace range with function call + var call = ts.createCall(ts.isClassLike(scope) ? ts.createPropertyAccess(range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.getText()) : ts.createThis(), functionReference) : functionReference, + /*typeArguments*/ undefined, callArguments); + if (range.facts & RangeFacts.IsGenerator) { + call = ts.createYield(ts.createToken(39 /* AsteriskToken */), call); + } + if (range.facts & RangeFacts.IsAsyncFunction) { + call = ts.createAwait(call); + } + if (writes) { + if (returnValueProperty) { + // has both writes and return, need to create variable declaration to hold return value; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119 /* AnyKeyword */))])); + } + var assignments = getPropertyAssignmentsForWrites(writes); + if (returnValueProperty) { + assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); + } + // propagate writes back + if (assignments.length === 1) { + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + else { + newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58 /* EqualsToken */, call))); + } + } + else { + // emit e.g. + // { a, b, __return } = newFunction(a, b); + // return __return; + newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58 /* EqualsToken */, call))); + if (returnValueProperty) { + newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); + } + } + } + else { + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn(call)); + } + else if (isReadonlyArray(range.range)) { + newNodes.push(ts.createStatement(call)); + } + else { + newNodes.push(call); + } + } + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { + nodeSeparator: context.newLineCharacter, + suffix: context.newLineCharacter // insert newline only when replacing statements + }); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); + } + return { + scope: scope, + scopeDescription: getDescriptionForScope(scope), + changes: changeTracker.getChanges() + }; + function getPropertyAssignmentsForWrites(writes) { + return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + } + function generateReturnValueProperty() { + return "__return"; + } + function transformFunctionBody(body) { + if (ts.isBlock(body) && !writes && substitutions.size === 0) { + // already block, no writes to propagate back, no substitutions - can use node as is + return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; + } + var returnValueProperty; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions + if (writes || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (writes && !(range.facts & RangeFacts.HasReturn) && ts.isStatement(body)) { + // add return at the end to propagate writes back in case if control flow falls out of the function body + // it is ok to know that range has at least one return since it we only allow unconditional returns + var assignments = getPropertyAssignmentsForWrites(writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; + } + function visitor(node) { + if (node.kind === 219 /* ReturnStatement */ && writes) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = generateReturnValueProperty(); + } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); + } + else { + return ts.createReturn(ts.createObjectLiteral(assignments)); + } + } + else { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } + } } - function createClassFromVariableDeclaration(node) { - var initializer = node.initializer; - if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { + extractMethod_1.extractFunctionInScope = extractFunctionInScope; + function isReadonlyArray(v) { + return ts.isArray(v); + } + /** + * Produces a range that spans the entirety of nodes, given a selection + * that might start/end in the middle of nodes. + * + * For example, when the user makes a selection like this + * v---v + * var someThing = foo + bar; + * this returns ^-------^ + */ + function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) + ? { pos: targetRange.range[0].getStart(sourceFile), end: targetRange.range[targetRange.range.length - 1].getEnd() } + : targetRange.range; + } + var Usage; + (function (Usage) { + // value should be passed to extracted method + Usage[Usage["Read"] = 1] = "Read"; + // value should be passed to extracted method and propagated back + Usage[Usage["Write"] = 2] = "Write"; + })(Usage || (Usage = {})); + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker) { + var usagesPerScope = []; + var substitutionsPerScope = []; + var errorsPerScope = []; + var visibleDeclarationsInExtractedRange = []; + // initialize results + for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { + var _ = scopes_1[_i]; + usagesPerScope.push({ usages: ts.createMap(), substitutions: ts.createMap() }); + substitutionsPerScope.push(ts.createMap()); + errorsPerScope.push([]); + } + var seenUsages = ts.createMap(); + var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); + collectUsages(target); + var _loop_8 = function (i) { + var hasWrite = false; + var readonlyClassPropertyWrite = undefined; + usagesPerScope[i].usages.forEach(function (value) { + if (value.usage === 2 /* Write */) { + hasWrite = true; + if (value.symbol.flags & 106500 /* ClassMember */ && + value.symbol.valueDeclaration && + ts.hasModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { + readonlyClassPropertyWrite = value.symbol.valueDeclaration; + } + } + }); + if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { + errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); + } + else if (readonlyClassPropertyWrite && i > 0) { + errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotCombineWritesAndReturns)); + } + }; + for (var i = 0; i < scopes.length; i++) { + _loop_8(i); + } + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + function collectUsages(node, valueUsage) { + if (valueUsage === void 0) { valueUsage = 1 /* Read */; } + if (ts.isDeclaration(node) && node.symbol) { + visibleDeclarationsInExtractedRange.push(node.symbol); + } + if (ts.isAssignmentExpression(node)) { + // use 'write' as default usage for values + collectUsages(node.left, 2 /* Write */); + collectUsages(node.right); + } + else if (ts.isUnaryExpressionWithWrite(node)) { + collectUsages(node.operand, 2 /* Write */); + } + else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { + // use 'write' as default usage for values + ts.forEachChild(node, collectUsages); + } + else if (ts.isIdentifier(node)) { + if (!node.parent) { + return; + } + if (ts.isQualifiedName(node.parent) && node !== node.parent.left) { + return; + } + if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { + return; + } + recordUsage(node, valueUsage, /*isTypeNode*/ ts.isPartOfTypeNode(node)); + } + else { + ts.forEachChild(node, collectUsages); + } + } + function recordUsage(n, usage, isTypeNode) { + var symbolId = recordUsagebySymbol(n, usage, isTypeNode); + if (symbolId) { + for (var i = 0; i < scopes.length; i++) { + // push substitution from map to map to simplify rewriting + var substitition = substitutionsPerScope[i].get(symbolId); + if (substitition) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitition); + } + } + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + var symbol = checker.getSymbolAtLocation(identifier); + if (!symbol) { + // cannot find symbol - do nothing + return undefined; + } + var symbolId = ts.getSymbolId(symbol).toString(); + var lastUsage = seenUsages.get(symbolId); + // there are two kinds of value usages + // - reads - if range contains a read from the value located outside of the range then value should be passed as a parameter + // - writes - if range contains a write to a value located outside the range the value should be passed as a parameter and + // returned as a return value + // 'write' case is a superset of 'read' so if we already have processed 'write' of some symbol there is not need to handle 'read' + // since all information is already recorded + if (lastUsage && lastUsage >= usage) { + return symbolId; + } + seenUsages.set(symbolId, usage); + if (lastUsage) { + // if we get here this means that we are trying to handle 'write' and 'read' was already processed + // walk scopes and update existing records. + for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) { + var perScope = usagesPerScope_1[_i]; + var prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) { + perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + return symbolId; + } + // find first declaration in this file + var declInFile = ts.find(symbol.getDeclarations(), function (d) { return d.getSourceFile() === sourceFile; }); + if (!declInFile) { + return undefined; + } + if (ts.rangeContainsRange(enclosingTextRange, declInFile)) { + // declaration is located in range to be extracted - do nothing + return undefined; + } + if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) { + // this is write to a reference located outside of the target scope and range is extracted into generator + // currently this is unsupported scenario + for (var _a = 0, errorsPerScope_1 = errorsPerScope; _a < errorsPerScope_1.length; _a++) { + var errors = errorsPerScope_1[_a]; + errors.push(ts.createDiagnosticForNode(identifier, Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators)); + } + } + for (var i = 0; i < scopes.length; i++) { + var scope = scopes[i]; + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + if (resolvedSymbol === symbol) { + continue; + } + if (!substitutionsPerScope[i].has(symbolId)) { + var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) { + substitutionsPerScope[i].set(symbolId, substitution); + } + else if (isTypeName) { + errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + } + else { + usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); + } + } + } + return symbolId; + } + function checkForUsedDeclarations(node) { + // If this node is entirely within the original extraction range, we don't need to do anything. + if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) { + return; + } + // Otherwise check and recurse. + var sym = checker.getSymbolAtLocation(node); + if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { + for (var _i = 0, errorsPerScope_2 = errorsPerScope; _i < errorsPerScope_2.length; _i++) { + var scope = errorsPerScope_2[_i]; + scope.push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + } + return true; + } + else { + ts.forEachChild(node, checkForUsedDeclarations); + } + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { + if (!symbol) { + return undefined; + } + if (symbol.getDeclarations().some(function (d) { return d.parent === scopeDecl; })) { + return ts.createIdentifier(symbol.name); + } + var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode); + if (prefix === undefined) { + return undefined; + } + return isTypeNode ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) : ts.createPropertyAccess(prefix, symbol.name); + } + } + function getParentNodeInSpan(node, file, span) { + if (!node) return undefined; + while (node.parent) { + if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) { + return node; + } + node = node.parent; } - 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)); - } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); - // Don't call copyComments here because we'll already leave them in place - return cls; } - function createClassFromFunctionDeclaration(node) { - var memberElements = createClassElementsFromSymbol(ctorSymbol); - if (node.body) { - memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); - } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); - // Don't call copyComments here because we'll already leave them in place - return cls; + function spanContainsNode(span, node, file) { + return ts.textSpanContainsPosition(span, node.getStart(file)) && + node.getEnd() <= ts.textSpanEnd(span); } - } + /** + * Computes whether or not a node represents an expression in a position where it could + * be extracted. + * The isExpression() in utilities.ts returns some false positives we need to handle, + * such as `import x from 'y'` -- the 'y' is a StringLiteral but is *not* an expression + * in the sense of something that you could extract on + */ + function isExtractableExpression(node) { + switch (node.parent.kind) { + case 264 /* EnumMember */: + return false; + } + switch (node.kind) { + case 9 /* StringLiteral */: + return node.parent.kind !== 238 /* ImportDeclaration */ && + node.parent.kind !== 242 /* ImportSpecifier */; + case 198 /* SpreadElement */: + case 174 /* ObjectBindingPattern */: + case 176 /* BindingElement */: + return false; + case 71 /* Identifier */: + return node.parent.kind !== 176 /* BindingElement */ && + node.parent.kind !== 242 /* ImportSpecifier */ && + node.parent.kind !== 246 /* ExportSpecifier */; + } + return true; + } + function isBlockLike(node) { + switch (node.kind) { + case 207 /* Block */: + case 265 /* SourceFile */: + case 234 /* ModuleBlock */: + case 257 /* CaseClause */: + return true; + default: + return false; + } + } + })(extractMethod = refactor.extractMethod || (refactor.extractMethod = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /// +/// /// /// /// @@ -89074,7 +90729,7 @@ var ts; node.parent = parent; return node; } - var NodeObject = (function () { + var NodeObject = /** @class */ (function () { function NodeObject(kind, pos, end) { this.pos = pos; this.end = end; @@ -89117,12 +90772,14 @@ var ts; ts.scanner.setTextPos(pos); while (pos < end) { var token = ts.scanner.scan(); - ts.Debug.assert(token !== 1 /* EndOfFileToken */); // Else it would infinitely loop var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); } pos = textPos; + if (token === 1 /* EndOfFileToken */) { + break; + } } return pos; }; @@ -89227,7 +90884,7 @@ var ts; }; return NodeObject; }()); - var TokenOrIdentifierObject = (function () { + var TokenOrIdentifierObject = /** @class */ (function () { function TokenOrIdentifierObject(pos, end) { // Set properties in same order as NodeObject this.pos = pos; @@ -89282,7 +90939,7 @@ var ts; }; return TokenOrIdentifierObject; }()); - var SymbolObject = (function () { + var SymbolObject = /** @class */ (function () { function SymbolObject(flags, name) { this.flags = flags; this.escapedName = name; @@ -89320,7 +90977,7 @@ var ts; }; return SymbolObject; }()); - var TokenObject = (function (_super) { + var TokenObject = /** @class */ (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { var _this = _super.call(this, pos, end) || this; @@ -89329,7 +90986,7 @@ var ts; } return TokenObject; }(TokenOrIdentifierObject)); - var IdentifierObject = (function (_super) { + var IdentifierObject = /** @class */ (function (_super) { __extends(IdentifierObject, _super); function IdentifierObject(_kind, pos, end) { return _super.call(this, pos, end) || this; @@ -89344,7 +91001,7 @@ var ts; return IdentifierObject; }(TokenOrIdentifierObject)); IdentifierObject.prototype.kind = 71 /* Identifier */; - var TypeObject = (function () { + var TypeObject = /** @class */ (function () { function TypeObject(checker, flags) { this.checker = checker; this.flags = flags; @@ -89386,7 +91043,7 @@ var ts; }; return TypeObject; }()); - var SignatureObject = (function () { + var SignatureObject = /** @class */ (function () { function SignatureObject(checker) { this.checker = checker; } @@ -89416,7 +91073,7 @@ var ts; }; return SignatureObject; }()); - var SourceFileObject = (function (_super) { + var SourceFileObject = /** @class */ (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { return _super.call(this, kind, pos, end) || this; @@ -89587,7 +91244,7 @@ var ts; }; return SourceFileObject; }(NodeObject)); - var SourceMapSourceObject = (function () { + var SourceMapSourceObject = /** @class */ (function () { function SourceMapSourceObject(fileName, text, skipTrivia) { this.fileName = fileName; this.text = text; @@ -89656,7 +91313,7 @@ var ts; // Cache host information about script Should be refreshed // at each language service public entry point, since we don't know when // the set of scripts handled by the host changes. - var HostCache = (function () { + var HostCache = /** @class */ (function () { function HostCache(host, getCanonicalFileName) { this.host = host; // script id => script index @@ -89718,7 +91375,7 @@ var ts; }; return HostCache; }()); - var SyntaxTreeCache = (function () { + var SyntaxTreeCache = /** @class */ (function () { function SyntaxTreeCache(host) { this.host = host; } @@ -89813,7 +91470,7 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - var CancellationTokenObject = (function () { + var CancellationTokenObject = /** @class */ (function () { function CancellationTokenObject(cancellationToken) { this.cancellationToken = cancellationToken; } @@ -89829,7 +91486,7 @@ var ts; }()); /* @internal */ /** A cancellation that throttles calls to the host */ - var ThrottledCancellationToken = (function () { + var ThrottledCancellationToken = /** @class */ (function () { function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) { if (throttleWaitMilliseconds === void 0) { throttleWaitMilliseconds = 20; } this.hostCancellationToken = hostCancellationToken; @@ -89980,8 +91637,8 @@ var ts; if (program) { var oldSourceFiles = program.getSourceFiles(); var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); } @@ -90038,7 +91695,7 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + path); + ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path); return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } // We didn't already have the file. Fall through and acquire it from the registry. @@ -90447,17 +92104,19 @@ var ts; function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var settings = toEditorSettings(options); - if (key === "{") { - return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + if (!ts.isInComment(sourceFile, position)) { + if (key === "{") { + return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "}") { + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === ";") { + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "\n") { + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + } } return []; } @@ -90504,6 +92163,11 @@ var ts; } return true; } + function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine); + return range && ts.createTextSpanFromRange(range); + } function getTodoComments(fileName, descriptors) { // Note: while getting todo comments seems like a syntactic operation, we actually // treat it as a semantic operation here. This is because we expect our host to call @@ -90693,6 +92357,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, @@ -90777,12 +92442,17 @@ var ts; function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(node.name)); - if (name && contextualType) { + return getPropertySymbolsFromType(contextualType, node.name); + } + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + /* @internal */ + function getPropertySymbolsFromType(type, propName) { + var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); + if (name && type) { var result_10 = []; - var symbol = contextualType.getProperty(name); - if (contextualType.flags & 65536 /* Union */) { - ts.forEach(contextualType.types, function (t) { + var symbol = type.getProperty(name); + if (type.flags & 65536 /* Union */) { + ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { result_10.push(symbol); @@ -90797,7 +92467,7 @@ var ts; } return undefined; } - ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + ts.getPropertySymbolsFromType = getPropertySymbolsFromType; function isArgumentOfElementAccessExpression(node) { return node && node.parent && @@ -91352,7 +93022,7 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 212 /* DoStatement */ || + if (node.parent.kind === 212 /* DoStatement */ || // Go to while keyword and do action instead node.parent.kind === 181 /* CallExpression */ || node.parent.kind === 182 /* NewExpression */) { return spanInPreviousNode(node); @@ -91471,7 +93141,7 @@ var ts; logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); } } - var ScriptSnapshotShimAdapter = (function () { + var ScriptSnapshotShimAdapter = /** @class */ (function () { function ScriptSnapshotShimAdapter(scriptSnapshotShim) { this.scriptSnapshotShim = scriptSnapshotShim; } @@ -91499,7 +93169,7 @@ var ts; }; return ScriptSnapshotShimAdapter; }()); - var LanguageServiceShimHostAdapter = (function () { + var LanguageServiceShimHostAdapter = /** @class */ (function () { function LanguageServiceShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; @@ -91623,7 +93293,7 @@ var ts; return LanguageServiceShimHostAdapter; }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; - var CoreServicesShimHostAdapter = (function () { + var CoreServicesShimHostAdapter = /** @class */ (function () { function CoreServicesShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; @@ -91688,7 +93358,7 @@ var ts; return JSON.stringify({ error: err }); } } - var ShimBase = (function () { + var ShimBase = /** @class */ (function () { function ShimBase(factory) { this.factory = factory; factory.registerShim(this); @@ -91712,7 +93382,7 @@ var ts; code: diagnostic.code }; } - var LanguageServiceShimObject = (function (_super) { + var LanguageServiceShimObject = /** @class */ (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { var _this = _super.call(this, factory) || this; @@ -91878,6 +93548,10 @@ var ts; var _this = this; return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); }); }; + LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) { + var _this = this; + return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); }); + }; /// GET SMART INDENT LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { var _this = this; @@ -91985,7 +93659,7 @@ var ts; function convertClassifications(classifications) { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } - var ClassifierShimObject = (function (_super) { + var ClassifierShimObject = /** @class */ (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { var _this = _super.call(this, factory) || this; @@ -92012,7 +93686,7 @@ var ts; }; return ClassifierShimObject; }(ShimBase)); - var CoreServicesShimObject = (function (_super) { + var CoreServicesShimObject = /** @class */ (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { var _this = _super.call(this, factory) || this; @@ -92119,7 +93793,7 @@ var ts; }; return CoreServicesShimObject; }(ShimBase)); - var TypeScriptServicesFactory = (function () { + var TypeScriptServicesFactory = /** @class */ (function () { function TypeScriptServicesFactory() { this._shims = []; } @@ -92200,4 +93874,6 @@ var TypeScript; // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "2.5"; +var toolsVersion = "2.6"; + +//# sourceMappingURL=typescriptServices.js.map diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 0aea3ef235..5f69ba3ddc 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -14,6 +14,14 @@ and limitations under the License. ***************************************************************************** */ "use strict"; +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -26,12 +34,443 @@ 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["JSDocNullableType"] = 270] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 292] = "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"] = 285] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "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["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; + 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"; @@ -56,6 +495,47 @@ var ts; 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"] = 4] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + })(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"; @@ -70,6 +550,230 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; + SymbolFlags[SymbolFlags["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"] = 2097152] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; + SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; + SymbolFlags[SymbolFlags["Classifiable"] = 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 InternalSymbolName; + (function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["Resolving"] = "__resolving__"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); + var NodeCheckFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["String"] = 2] = "String"; + TypeFlags[TypeFlags["Number"] = 4] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; + TypeFlags[TypeFlags["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 InferencePriority; + (function (InferencePriority) { + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; + })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + var InferenceFlags; + (function (InferenceFlags) { + InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; + InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + var Ternary; + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(Ternary = ts.Ternary || (ts.Ternary = {})); + var SpecialPropertyAssignmentKind; + (function (SpecialPropertyAssignmentKind) { + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -91,6 +795,310 @@ var ts; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + ScriptKind[ScriptKind["External"] = 5] = "External"; + ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["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["Ts"] = ".ts"; + Extension["Tsx"] = ".tsx"; + Extension["Dts"] = ".d.ts"; + Extension["Js"] = ".js"; + Extension["Jsx"] = ".jsx"; + })(Extension = ts.Extension || (ts.Extension = {})); + var TransformFlags; + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; + TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; + TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; + TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; + TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["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["ExportStar"] = 32768] = "ExportStar"; + 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"] = 32768] = "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) { @@ -153,7 +1161,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.5"; + ts.versionMajorMinor = "2.6"; ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { @@ -267,6 +1275,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; } @@ -438,10 +1452,9 @@ var ts; ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (f(item)) { - array[outIndex] = item; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; outIndex++; } } @@ -487,8 +1500,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -558,11 +1571,13 @@ var ts; ts.sameFlatMap = sameFlatMap; function mapDefined(array, mapFn) { var result = []; - for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); - if (mapped !== undefined) { - result.push(mapped); + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } } } return result; @@ -630,8 +1645,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; if (predicate(v)) { return true; } @@ -656,8 +1671,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var item = array_6[_i]; + loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -745,8 +1760,8 @@ var ts; ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var v = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -1006,8 +2021,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var value = array_8[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; @@ -1167,11 +2182,11 @@ var ts; ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { var end = start + length; - Debug.assert(start >= 0, "start must be non-negative, is " + start); - Debug.assert(length >= 0, "length must be non-negative, is " + length); + Debug.assertGreaterThanOrEqual(start, 0); + Debug.assertGreaterThanOrEqual(length, 0); if (file) { - Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); - Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + Debug.assertLessThanOrEqual(start, file.text.length); + Debug.assertLessThanOrEqual(end, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -1380,19 +2395,23 @@ var ts; return normalized; } function normalizePath(path) { + return normalizePathAndParts(path).path; + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { path = normalizeSlashes(path); var rootLength = getRootLength(path); var root = path.substr(0, rootLength); - var normalized = getNormalizedParts(path, rootLength); - if (normalized.length) { - var joinedParts = root + normalized.join(ts.directorySeparator); - return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts; + var parts = getNormalizedParts(path, rootLength); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; } else { - return root; + return { path: root, parts: parts }; } } - ts.normalizePath = normalizePath; + ts.normalizePathAndParts = normalizePathAndParts; function pathEndsWithDirectorySeparator(path) { return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; } @@ -1655,8 +2674,28 @@ var ts; ts.fileExtensionIsOneOf = fileExtensionIsOneOf; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; - var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; - var singleAsteriskRegexFragmentOther = "[^/]*"; + ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; + var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var filesMatcher = { + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } + }; + var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } + }; + var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); } + }; + var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher + }; function getRegularExpressionForWildcard(specs, basePath, usage) { var patterns = getRegularExpressionsForWildcards(specs, basePath, usage); if (!patterns || !patterns.length) { @@ -1671,18 +2710,16 @@ var ts; if (specs === undefined || specs.length === 0) { return undefined; } - var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; - var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; - var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; return flatMap(specs, function (spec) { - return spec && getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } function isImplicitGlob(lastPathComponent) { return !/[.*?]/.test(lastPathComponent); } ts.isImplicitGlob = isImplicitGlob; - function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; @@ -1714,16 +2751,24 @@ var ts; subpattern += ts.directorySeparator; } if (usage !== "exclude") { + var componentPattern = ""; if (component.charCodeAt(0) === 42) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; component = component.substr(1); } else if (component.charCodeAt(0) === 63) { - subpattern += "[^./]"; + componentPattern += "[^./]"; component = component.substr(1); } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } + else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); } hasWrittenComponent = true; } @@ -1733,12 +2778,6 @@ var ts; } return subpattern; } - function replaceWildCardCharacterFiles(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); - } - function replaceWildCardCharacterOther(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); - } function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } @@ -1875,14 +2914,7 @@ var ts; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = allSupportedExtensions.slice(0); - for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { - var extInfo = extraFileExtensions_1[_i]; - if (extensions.indexOf(extInfo.extension) === -1) { - extensions.push(extInfo.extension); - } - } - return extensions; + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -1906,6 +2938,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])) { @@ -1999,6 +3038,13 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; + var AssertionLevel; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; @@ -2010,12 +3056,37 @@ var ts; function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { if (verboseDebugInfo) { - message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); } fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; + function assertEqual(a, b, msg, msg2) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || "")); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b) { + if (a > b) { + fail("Expected " + a + " <= " + b); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b) { + if (a < b) { + fail("Expected " + a + " >= " + b); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; function fail(message, stackCrawlMark) { debugger; var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); @@ -2150,6 +3221,10 @@ var ts; Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; function tryGetExtensionFromPath(path) { return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } @@ -2161,6 +3236,12 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function setStackTraceLimit() { + if (Error.stackTraceLimit < 100) { + Error.stackTraceLimit = 100; + } + } + ts.setStackTraceLimit = setStackTraceLimit; var FileWatcherEventKind; (function (FileWatcherEventKind) { FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; @@ -2210,7 +3291,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -2334,6 +3415,11 @@ var ts; function readDirectory(path, extensions, excludes, includes, depth) { return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, 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); @@ -3031,6 +4117,8 @@ var ts; Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -3218,6 +4306,7 @@ var ts; Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -3471,6 +4560,8 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), + Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), + Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), }; })(ts || (ts = {})); var ts; @@ -3491,19 +4582,6 @@ var ts; return undefined; } ts.getDeclarationOfKind = getDeclarationOfKind; - function findDeclaration(symbol, predicate) { - var declarations = symbol.declarations; - if (declarations) { - for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { - var declaration = declarations_2[_i]; - if (predicate(declaration)) { - return declaration; - } - } - } - return undefined; - } - ts.findDeclaration = findDeclaration; var stringWriter = createSingleLineStringWriter(); var stringWriterAcquired = false; function createSingleLineStringWriter() { @@ -3566,9 +4644,13 @@ var ts; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && - oldResolution.resolvedFileName === newResolution.resolvedFileName; + oldResolution.resolvedFileName === newResolution.resolvedFileName && + packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function packageIdIsEqual(a, b) { + return a === b || a && b && a.name === b.name && a.version === b.version; + } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -3633,14 +4715,6 @@ var ts; return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; } ts.nodePosToString = nodePosToString; - function getStartPosOfNode(node) { - return node.pos; - } - ts.getStartPosOfNode = getStartPosOfNode; - function isDefined(value) { - return value !== undefined; - } - ts.isDefined = isDefined; function getEndLinePosition(line, sourceFile) { ts.Debug.assert(line >= 0); var lineStarts = ts.getLineStarts(sourceFile); @@ -3671,6 +4745,25 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + if (text.charCodeAt(commentPos + 1) === 47 && + commentPos + 2 < commentEnd && + text.charCodeAt(commentPos + 2) === 47) { + var textSubStr = text.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || + textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) || + textSubStr.match(defaultLibReferenceRegEx) ? + true : false; + } + return false; + } + ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; + function isPinnedComment(text, comment) { + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 33; + } + ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { if (nodeIsMissing(node)) { return node.pos; @@ -3727,15 +4820,20 @@ var ts; var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: - return '"' + escapeText(node.text) + '"'; + if (node.singleQuote) { + return "'" + escapeText(node.text, 39) + "'"; + } + else { + return '"' + escapeText(node.text, 34) + '"'; + } case 13: - return "`" + escapeText(node.text) + "`"; + return "`" + escapeText(node.text, 96) + "`"; case 14: - return "`" + escapeText(node.text) + "${"; + return "`" + escapeText(node.text, 96) + "${"; case 15: - return "}" + escapeText(node.text) + "${"; + return "}" + escapeText(node.text, 96) + "${"; case 16: - return "}" + escapeText(node.text) + "`"; + return "}" + escapeText(node.text, 96) + "`"; case 8: return node.text; } @@ -3987,13 +5085,9 @@ var ts; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); + return node.kind !== 10 ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; - function getLeadingCommentRangesOfNodeFromText(node, text) { - return ts.getLeadingCommentRanges(text, node.pos); - } - ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; function getJSDocCommentRanges(node, text) { var commentRanges = (node.kind === 146 || node.kind === 145 || @@ -4001,7 +5095,7 @@ var ts; node.kind === 187 || node.kind === 185) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : - getLeadingCommentRangesOfNodeFromText(node, text); + ts.getLeadingCommentRanges(text, node.pos); return ts.filter(commentRanges, function (comment) { return text.charCodeAt(comment.pos + 1) === 42 && text.charCodeAt(comment.pos + 2) === 42 && @@ -4010,8 +5104,9 @@ var ts; } ts.getJSDocCommentRanges = getJSDocCommentRanges; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; - ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { if (158 <= node.kind && node.kind <= 173) { return true; @@ -4238,21 +5333,11 @@ var ts; } ts.getPropertyAssignment = getPropertyAssignment; function getContainingFunction(node) { - while (true) { - node = node.parent; - if (!node || ts.isFunctionLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isFunctionLike); } ts.getContainingFunction = getContainingFunction; function getContainingClass(node) { - while (true) { - node = node.parent; - if (!node || ts.isClassLike(node)) { - return node; - } - } + return ts.findAncestor(node.parent, ts.isClassLike); } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { @@ -4859,6 +5944,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) { @@ -5056,14 +6147,14 @@ var ts; ts.getAncestor = getAncestor; function getFileReferenceFromReferencePath(comment, commentRange) { var simpleReferenceRegEx = /^\/\/\/\s*/gim; + var isNoDefaultLibRegEx = new RegExp(defaultLibReferenceRegEx.source, "gim"); if (simpleReferenceRegEx.test(comment)) { if (isNoDefaultLibRegEx.test(comment)) { return { isNoDefaultLib: true }; } else { var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); - var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); + var refLibResult = !refMatchResult && fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); var match = refMatchResult || refLibResult; if (match) { var pos = commentRange.pos + match[1].length + match[2].length; @@ -5094,6 +6185,14 @@ 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; @@ -5244,10 +6343,11 @@ var ts; return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } ts.getOriginalSourceFile = getOriginalSourceFile; - function getOriginalSourceFiles(sourceFiles) { - return ts.sameMap(sourceFiles, getOriginalSourceFile); - } - ts.getOriginalSourceFiles = getOriginalSourceFiles; + 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; @@ -5481,7 +6581,9 @@ var ts; } } ts.createDiagnosticCollection = createDiagnosticCollection; - var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\0": "\\0", "\t": "\\t", @@ -5492,11 +6594,16 @@ var ts; "\n": "\\n", "\\": "\\\\", "\"": "\\\"", + "\'": "\\\'", + "\`": "\\\`", "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" }); - function escapeString(s) { + function escapeString(s, quoteChar) { + var escapedCharsRegExp = quoteChar === 96 ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; return s.replace(escapedCharsRegExp, getReplacement); } ts.escapeString = escapeString; @@ -5514,8 +6621,8 @@ var ts; return "\\u" + paddedHexCode; } var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiString(s) { - s = escapeString(s); + function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; @@ -5856,7 +6963,7 @@ var ts; var currentDetachedCommentInfo; if (removeComments) { if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); } } else { @@ -5888,9 +6995,8 @@ var ts; } } return currentDetachedCommentInfo; - function isPinnedComment(comment) { - return text.charCodeAt(comment.pos + 1) === 42 && - text.charCodeAt(comment.pos + 2) === 33; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment); } } ts.emitDetachedComments = emitDetachedComments; @@ -5961,9 +7067,13 @@ var ts; } ts.hasModifiers = hasModifiers; function hasModifier(node, flags) { - return (getModifierFlags(node) & flags) !== 0; + return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function getSelectedModifierFlags(node, flags) { + return getModifierFlags(node) & flags; + } + ts.getSelectedModifierFlags = getSelectedModifierFlags; function getModifierFlags(node) { if (node.modifierFlagsCache & 536870912) { return node.modifierFlagsCache & ~536870912; @@ -6039,21 +7149,6 @@ var ts; return false; } ts.isDestructuringAssignment = isDestructuringAssignment; - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 71) { - return true; - } - else if (ts.isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } - } function isExpressionWithTypeArgumentsInClassExtendsClause(node) { return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } @@ -6166,72 +7261,6 @@ var ts; return carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; - function isSimpleExpression(node) { - return isSimpleExpressionWorker(node, 0); - } - ts.isSimpleExpression = isSimpleExpression; - function isSimpleExpressionWorker(node, depth) { - if (depth <= 5) { - var kind = node.kind; - if (kind === 9 - || kind === 8 - || kind === 12 - || kind === 13 - || kind === 71 - || kind === 99 - || kind === 97 - || kind === 101 - || kind === 86 - || kind === 95) { - return true; - } - else if (kind === 179) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 180) { - return isSimpleExpressionWorker(node.expression, depth + 1) - && isSimpleExpressionWorker(node.argumentExpression, depth + 1); - } - else if (kind === 192 - || kind === 193) { - return isSimpleExpressionWorker(node.operand, depth + 1); - } - else if (kind === 194) { - return node.operatorToken.kind !== 40 - && isSimpleExpressionWorker(node.left, depth + 1) - && isSimpleExpressionWorker(node.right, depth + 1); - } - else if (kind === 195) { - return isSimpleExpressionWorker(node.condition, depth + 1) - && isSimpleExpressionWorker(node.whenTrue, depth + 1) - && isSimpleExpressionWorker(node.whenFalse, depth + 1); - } - else if (kind === 190 - || kind === 189 - || kind === 188) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 177) { - return node.elements.length === 0; - } - else if (kind === 178) { - return node.properties.length === 0; - } - else if (kind === 181) { - if (!isSimpleExpressionWorker(node.expression, depth + 1)) { - return false; - } - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (!isSimpleExpressionWorker(argument, depth + 1)) { - return false; - } - } - return true; - } - } - return false; - } function formatEnum(value, enumObject, isFlags) { if (value === void 0) { value = 0; } var members = getEnumMembers(enumObject); @@ -6300,18 +7329,6 @@ var ts; return formatEnum(flags, ts.ObjectFlags, true); } ts.formatObjectFlags = formatObjectFlags; - function getRangePos(range) { - return range ? range.pos : -1; - } - ts.getRangePos = getRangePos; - function getRangeEnd(range) { - return range ? range.end : -1; - } - ts.getRangeEnd = getRangeEnd; - function movePos(pos, value) { - return ts.positionIsSynthesized(pos) ? -1 : pos + value; - } - ts.movePos = movePos; function createRange(pos, end) { return { pos: pos, end: end }; } @@ -6340,14 +7357,6 @@ var ts; return range.pos === range.end; } ts.isCollapsedRange = isCollapsedRange; - function collapseRangeToStart(range) { - return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); - } - ts.collapseRangeToStart = collapseRangeToStart; - function collapseRangeToEnd(range) { - return isCollapsedRange(range) ? range : moveRangePos(range, range.end); - } - ts.collapseRangeToEnd = collapseRangeToEnd; function createTokenRange(pos, token) { return createRange(pos, pos + ts.tokenToString(token).length); } @@ -6400,22 +7409,6 @@ var ts; function isInitializedVariable(node) { return node.initializer !== undefined; } - function isMergedWithClass(node) { - if (node.symbol) { - for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 229 && declaration !== node) { - return true; - } - } - } - return false; - } - ts.isMergedWithClass = isMergedWithClass; - function isFirstDeclarationOfKind(node, kind) { - return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; - } - ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; function isWatchSet(options) { return options.watch && options.hasOwnProperty("watch"); } @@ -6616,6 +7609,20 @@ var ts; return ts.hasModifier(node, 92) && node.parent.kind === 152 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function isEmptyBindingPattern(node) { + if (ts.isBindingPattern(node)) { + return ts.every(node.elements, isEmptyBindingElement); + } + return false; + } + ts.isEmptyBindingPattern = isEmptyBindingPattern; + function isEmptyBindingElement(node) { + if (ts.isOmittedExpression(node)) { + return true; + } + return isEmptyBindingPattern(node.name); + } + ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { while (node && (node.kind === 176 || ts.isBindingPattern(node))) { node = node.parent; @@ -7696,6 +8703,18 @@ var ts; return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionWithWrite(expr) { + switch (expr.kind) { + case 193: + return true; + case 192: + return expr.operator === 43 || + expr.operator === 44; + default: + return false; + } + } + ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; function isExpressionKind(kind) { return kind === 195 || kind === 197 @@ -7880,9 +8899,19 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 207; + || isBlockStatement(node); } ts.isStatement = isStatement; + function isBlockStatement(node) { + if (node.kind !== 207) + return false; + if (node.parent !== undefined) { + if (node.parent.kind === 224 || node.parent.kind === 260) { + return false; + } + } + return !ts.isFunctionBlock(node); + } function isModuleReference(node) { var kind = node.kind; return kind === 248 @@ -9540,6 +10569,16 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; + SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; + SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; + SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList"; + SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; + SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; + })(SignatureFlags || (SignatureFlags = {})); var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -11377,11 +12416,31 @@ var ts; var node = parseTokenNode(); return token() === 23 ? undefined : node; } - function parseLiteralTypeNode() { + function parseLiteralTypeNode(negative) { var node = createNode(173); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; + var unaryMinusExpression; + if (negative) { + unaryMinusExpression = createNode(192); + unaryMinusExpression.operator = 38; + nextToken(); + } + var expression; + switch (token()) { + case 9: + case 8: + expression = parseLiteralLikeNode(token()); + break; + case 101: + case 86: + expression = parseTokenNode(); + } + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); } function nextTokenIsNumericLiteral() { return nextToken() === 8; @@ -11413,7 +12472,7 @@ var ts; case 86: return parseLiteralTypeNode(); case 38: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(true) : parseTypeReference(); case 105: case 95: return parseTokenNode(); @@ -11462,6 +12521,7 @@ var ts; case 101: case 86: case 134: + case 39: return true; case 38: return lookAhead(nextTokenIsNumericLiteral); @@ -11780,7 +12840,7 @@ var ts; if (!arrowFunction) { return undefined; } - var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); + var isAsync = ts.hasModifier(arrowFunction, 256); var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 36 || lastToken === 17) @@ -11896,7 +12956,7 @@ var ts; function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(187); node.modifiers = parseModifiersForArrowFunction(); - var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); if (!node.parameters) { return undefined; @@ -12629,7 +13689,7 @@ var ts; parseExpected(89); node.asteriskToken = parseOptionalToken(39); var isGenerator = node.asteriskToken ? 1 : 0; - var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -12854,10 +13914,13 @@ var ts; function parseCatchClause() { var result = createNode(260); parseExpected(74); - if (parseExpected(19)) { + if (parseOptional(19)) { result.variableDeclaration = parseVariableDeclaration(); + parseExpected(20); + } + else { + result.variableDeclaration = undefined; } - parseExpected(20); result.block = parseBlock(false); return finishNode(result); } @@ -13861,6 +14924,39 @@ 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["Count"] = 23] = "Count"; + })(ParsingContext || (ParsingContext = {})); + var Tristate; + (function (Tristate) { + Tristate[Tristate["False"] = 0] = "False"; + Tristate[Tristate["True"] = 1] = "True"; + Tristate[Tristate["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); var JSDocParser; (function (JSDocParser) { function parseJSDocTypeExpressionForTests(content, start, length) { @@ -13913,6 +15009,17 @@ var ts; var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; + var JSDocState; + (function (JSDocState) { + JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; + })(JSDocState || (JSDocState = {})); + var PropertyLikeParse; + (function (PropertyLikeParse) { + PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; + })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; start = start || 0; @@ -14545,8 +15652,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -14618,8 +15725,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -14767,6 +15874,10 @@ var ts; } } } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); })(ts || (ts = {})); var ts; @@ -15131,6 +16242,12 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "preserveSymlinks", + type: "boolean", + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, + }, { name: "sourceRoot", type: "string", @@ -15742,7 +16859,7 @@ var ts; var text = valueExpression.text; if (option && typeof option.type !== "string") { var customOption = option; - if (!customOption.type.has(text)) { + if (!customOption.type.has(text.toLowerCase())) { errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); } } @@ -15993,12 +17110,10 @@ var ts; } } else { - var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - specs.push(outDir); + excludeSpecs = [outDir]; } - excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; @@ -16249,7 +17364,7 @@ var ts; return value; } else if (typeof option.type !== "string") { - return option.type.get(value); + return option.type.get(typeof value === "string" ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -16324,23 +17439,13 @@ var ts; }; } function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { - var validSpecs = []; - for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { - var spec = specs_1[_i]; - if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); } - else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); - } - else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); - } - else { - validSpecs.push(spec); - } - } - return validSpecs; + return diag === undefined; + }); function createDiagnostic(message, spec) { if (jsonSourceFile && jsonSourceFile.jsonObject) { for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { @@ -16358,6 +17463,17 @@ var ts; return ts.createCompilerDiagnostic(message, spec); } } + function specToDiagnostic(spec, allowTrailingRecursion) { + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; + } + else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { + return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; + } + } function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); @@ -16482,12 +17598,20 @@ var ts; "crypto", "stream", "util", "assert", "tty", "domain", "constants", "process", "v8", "timers", "console" ]; - var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); + var nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); function loadSafeList(host, safeListPath) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); return ts.createMapFromTemplate(result.config); } JsTyping.loadSafeList = loadSafeList; + function loadTypesMap(host, typesMapPath) { + var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); + if (result.config) { + return ts.createMapFromTemplate(result.config.simpleMap); + } + return undefined; + } + JsTyping.loadTypesMap = loadTypesMap; function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; @@ -16639,6 +17763,7 @@ var ts; Arguments.LogFile = "--logFile"; Arguments.EnableTelemetry = "--enableTelemetry"; Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.TypesMapLocation = "--typesMapLocation"; Arguments.NpmLocation = "--npmLocation"; })(Arguments = server.Arguments || (server.Arguments = {})); function hasArgument(argumentName) { @@ -16664,6 +17789,12 @@ var ts; return compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; + function withPackageId(packageId, r) { + return r && { path: r.path, extension: r.ext, packageId: packageId }; + } + function noPackageId(r) { + return withPackageId(undefined, r); + } var Extensions; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; @@ -16679,12 +17810,11 @@ var ts; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } - function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); + function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { if (!ts.hasProperty(jsonContent, fieldName)) { @@ -16778,7 +17908,9 @@ var ts; } var resolvedTypeReferenceDirective; if (resolved) { - resolved = realpath(resolved, host, traceEnabled); + if (!options.preserveSymlinks) { + resolved = realPath(resolved, host, traceEnabled); + } if (traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); } @@ -17079,7 +18211,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension }; + return { path: path_1, extension: extension, packageId: undefined }; } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -17100,7 +18232,7 @@ var ts; 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(", ")); + throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } @@ -17126,16 +18258,22 @@ var ts; trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); - return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; + if (!resolved_1) + return undefined; + var resolvedValue = resolved_1.value; + if (!compilerOptions.preserveSymlinks) { + resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + } + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); - return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } } } - function realpath(path, host, traceEnabled) { + function realPath(path, host, traceEnabled) { if (!host.realpath) { return path; } @@ -17161,7 +18299,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return resolvedFromFile; + return noPackageId(resolvedFromFile); } } if (!onlyRecordFailures) { @@ -17179,6 +18317,9 @@ var ts; return !host.directoryExists || host.directoryExists(directoryName); } ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + } function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -17208,9 +18349,9 @@ var ts; case Extensions.JavaScript: return tryExtension(".js") || tryExtension(".jsx"); } - function tryExtension(extension) { - var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, extension: extension }; + function tryExtension(ext) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, ext: ext }; } } function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { @@ -17233,12 +18374,20 @@ var ts; function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + var packageId; if (considerPackageJson) { var packageJsonPath = pathToPackageJson(candidate); if (directoryExists && state.host.fileExists(packageJsonPath)) { - var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var jsonContent = readJson(packageJsonPath, state.host); + if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { + packageId = { name: jsonContent.name, version: jsonContent.version }; + } + var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); if (fromPackageJson) { - return fromPackageJson; + return withPackageId(packageId, fromPackageJson); } } else { @@ -17248,13 +18397,10 @@ var ts; failedLookupLocations.push(packageJsonPath); } } - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } - function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); if (!file) { return undefined; } @@ -17270,11 +18416,15 @@ var ts; } } var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + if (result) { + ts.Debug.assert(result.packageId === undefined); + return { path: result.path, ext: result.extension }; + } } function resolvedIfExtensionMatches(extensions, path) { - var extension = ts.tryGetExtensionFromPath(path); - return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; + var ext = ts.tryGetExtensionFromPath(path); + return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; } function extensionIsOk(extensions, extension) { switch (extensions) { @@ -17291,7 +18441,7 @@ var ts; } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { @@ -17365,7 +18515,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); } - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -17376,7 +18526,7 @@ var ts; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -17388,7 +18538,7 @@ var ts; return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, false, state)); }); if (resolved_3) { return resolved_3; @@ -17399,7 +18549,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, false, state)); } } } @@ -17488,11 +18638,12 @@ var ts; } typingsInstaller.validatePackageName = validatePackageName; var TypingsInstaller = (function () { - function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, throttleLimit, log) { + function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) { if (log === void 0) { log = nullLog; } this.installTypingHost = installTypingHost; this.globalCachePath = globalCachePath; this.safeListPath = safeListPath; + this.typesMapLocation = typesMapLocation; this.throttleLimit = throttleLimit; this.log = log; this.packageNameToTypingLocation = ts.createMap(); @@ -17503,7 +18654,7 @@ var ts; this.installRunCount = 1; this.inFlightRequestCount = 0; if (this.log.isEnabled()) { - this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "'"); + this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation); } this.processCacheLocation(this.globalCachePath); } @@ -17531,6 +18682,7 @@ var ts; } }; TypingsInstaller.prototype.install = function (req) { + var _this = this; if (this.log.isEnabled()) { this.log.writeLine("Got install request " + JSON.stringify(req)); } @@ -17541,9 +18693,9 @@ var ts; this.processCacheLocation(req.cachePath); } if (this.safeList === undefined) { - this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath); + this.initializeSafeList(); } - var discoverTypingsResult = ts.JsTyping.discoverTypings(this.installTypingHost, this.log.isEnabled() ? this.log.writeLine : undefined, req.fileNames, req.projectRootPath, this.safeList, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports); + var discoverTypingsResult = ts.JsTyping.discoverTypings(this.installTypingHost, this.log.isEnabled() ? (function (s) { return _this.log.writeLine(s); }) : undefined, req.fileNames, req.projectRootPath, this.safeList, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports); if (this.log.isEnabled()) { this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult)); } @@ -17558,6 +18710,18 @@ var ts; } } }; + TypingsInstaller.prototype.initializeSafeList = function () { + if (this.typesMapLocation) { + var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation); + if (safeListFromMap) { + this.log.writeLine("Loaded safelist from types map file '" + this.typesMapLocation + "'"); + this.safeList = safeListFromMap; + return; + } + this.log.writeLine("Failed to load safelist from types map file '" + this.typesMapLocation + "'"); + } + this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath); + }; TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) { if (this.log.isEnabled()) { this.log.writeLine("Processing cache location '" + cacheLocation + "'"); @@ -17727,14 +18891,15 @@ var ts; _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles))); } finally { - _this.sendResponse({ + var response = { kind: server.EventEndInstallTypes, eventId: requestId, projectName: req.projectName, packagesToInstall: scopedTypings, installSuccess: ok, typingsInstallerVersion: ts.version - }); + }; + _this.sendResponse(response); } }); }; @@ -17820,20 +18985,21 @@ var ts; var path = require("path"); var FileLog = (function () { function FileLog(logFile) { + var _this = this; this.logFile = logFile; this.logEnabled = true; + this.isEnabled = function () { + return _this.logEnabled && _this.logFile !== undefined; + }; + this.writeLine = function (text) { + try { + fs.appendFileSync(_this.logFile, text + ts.sys.newLine); + } + catch (e) { + _this.logEnabled = false; + } + }; } - FileLog.prototype.isEnabled = function () { - return this.logEnabled && this.logFile !== undefined; - }; - FileLog.prototype.writeLine = function (text) { - try { - fs.appendFileSync(this.logFile, text + ts.sys.newLine); - } - catch (e) { - this.logEnabled = false; - } - }; return FileLog; }()); function getDefaultNPMLocation(processName) { @@ -17868,8 +19034,8 @@ var ts; } var NodeTypingsInstaller = (function (_super) { __extends(NodeTypingsInstaller, _super); - function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, npmLocation, throttleLimit, log) { - var _this = _super.call(this, ts.sys, globalTypingsCacheLocation, typingSafeListLocation ? ts.toPath(typingSafeListLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this; + function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, throttleLimit, log) { + var _this = _super.call(this, ts.sys, globalTypingsCacheLocation, typingSafeListLocation ? ts.toPath(typingSafeListLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), typesMapLocation ? ts.toPath(typesMapLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typesMap.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this; _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0]); if (_this.npmPath.indexOf(" ") !== -1 && _this.npmPath[0] !== "\"") { _this.npmPath = "\"" + _this.npmPath + "\""; @@ -17884,7 +19050,7 @@ var ts; if (_this.log.isEnabled()) { _this.log.writeLine("Updating " + TypesRegistryPackageName + " npm package..."); } - _this.execSync(_this.npmPath + " install " + TypesRegistryPackageName, { cwd: globalTypingsCacheLocation, stdio: "ignore" }); + _this.execSync(_this.npmPath + " install --ignore-scripts " + TypesRegistryPackageName, { cwd: globalTypingsCacheLocation, stdio: "ignore" }); if (_this.log.isEnabled()) { _this.log.writeLine("Updated " + TypesRegistryPackageName + " npm package"); } @@ -17930,7 +19096,7 @@ var ts; if (this.log.isEnabled()) { this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(args) + "'."); } - var command = this.npmPath + " install " + args.join(" ") + " --save-dev --user-agent=\"typesInstaller/" + ts.version + "\""; + var command = this.npmPath + " install --ignore-scripts " + args.join(" ") + " --save-dev --user-agent=\"typesInstaller/" + ts.version + "\""; var start = Date.now(); var stdout; var stderr; @@ -17954,6 +19120,7 @@ var ts; var logFilePath = server.findArgument(server.Arguments.LogFile); var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation); var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); + var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation); var npmLocation = server.findArgument(server.Arguments.NpmLocation); var log = new FileLog(logFilePath); if (log.isEnabled()) { @@ -17967,8 +19134,10 @@ var ts; } process.exit(0); }); - var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, npmLocation, 5, log); + var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, 5, log); installer.listen(); })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); + +//# sourceMappingURL=typingsInstaller.js.map